实现从文件中截取出从一个字符串开始到另一个字符串结束,之间所有的字符输出到另一个文件中。下面的批处理脚本实现从1_DDL.out文件中将所有在CREATE和分号之间的行输出到0.txt中。(一个CREATE对应紧随其后的分号为一组)
@echo off
Rem matching and extracting the create table statements
if exist 1_DDL.out (
echo now extracting create table statements
set myflag=false
SetLocal EnableDelayedExpansion
for /f "delims=" %%i in (1_DDL.out) do (
echo %%i
echo %%i|find "CREATE">nul && set myflag=true
if "!myflag!" == "true" (
echo %%i >> 0.txt
rem echo %%i
) else (
echo not matching...
)
echo %%i|find ";">nul && set myflag=false
)
) else (
echo not found 1_DDL.out
)
Rem deleting the unused file
echo clearing the unused files
del 1_DDL.out
echo Done.
上述批处理代码,存在一个问题:当输入文件1_DDL.out中含有大于号>等特殊符号时,匹配失败,且会有各种“奇怪”的现象。大家有兴趣可以自己试验一下。下面是经过增强的版本2:
Rem matching and extracting the create table statements
if exist 1_DDL.out (
echo now extracting create table statements
set myflag=false
rem any good idea?
set tempflag=false
SetLocal EnableDelayedExpansion
for /f "delims=" %%i in (1_DDL.out) do (
echo %%i
rem tackling the > operator
rem echo "%%i"
set tempflag = false
echo %%i |find ";">nul && set tempflag=true
echo "%%i"|find /i "create">nul && set myflag=true
echo !myflag!
if "!myflag!" == "true" (
echo %%i >> DDL.txt
rem echo %%i
) else (
echo not matching...
)
rem the next sentence do nth if there is a > in current %%i
rem echo %%i|find ";">nul && set myflag=false
if "!tempflag!" == "true" set myflag=false
)
endlocal
) else (
echo not found 1_DDL.out
)
上面的实现用了两个flag变量,逻辑有点绕。特别注意一下%%i加了引号。下面是逻辑较为清晰的代码:
Rem matching and extracting the create table statements
if exist 1_DDL.out (
echo now extracting create table statements
set myflag=false
SetLocal EnableDelayedExpansion
for /f "delims=" %%i in (1_DDL.out) do (
echo %%i
rem tackling the > operator
echo "%%i"
echo "%%i"|find /i "create">nul && set myflag=true
echo myflag !myflag!
if "!myflag!" == "true" (
echo %%i >> DDL.txt
rem echo %%i
) else (
echo not matching...
)
echo "%%i"|find ";">nul && set myflag=false
)
endlocal
) else (
echo not found 1_DDL.out
)
今天(2012年11月26号)发现之前写的这个bat,
echo "%%i"|find /i "create">nul && set myflag=true
这行执行时会报错find: `create': No such file or directory或者The process tried to write to a nonexistent pipe,很诧异,之前执行都未出现此问题,google了一段时间没有找到解决办法。最后只能先改成findstr了。哪位大虾有解决办法共享下。