windows批处理(shell)多行字符串匹配

实现从文件中截取出从一个字符串开始到另一个字符串结束,之间所有的字符输出到另一个文件中。下面的批处理脚本实现从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了。哪位大虾有解决办法共享下。


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值