Board logo

标题: [文本处理] [已解决]批处理for命令使用的 if 带括号,运行时一闪而过无法正常运行 [打印本页]

作者: sishentibu    时间: 2016-9-25 08:44     标题: [已解决]批处理for命令使用的 if 带括号,运行时一闪而过无法正常运行

先看代码
  1. @echo off
  2. setlocal enabledelayedexpansion
  3. cd /d %~dp0
  4. echo.>ip_output.txt
  5. for /f "tokens=1-3" %%i in (ip_tmpok.txt) do (
  6. set tp=%%j
  7. if !tp:~0,3!==NA_ (
  8. set t=!tp:NA_=!
  9. set err=1 ) else (
  10. set err=0
  11. )
  12. (echo %%i %%k gws !t! !err! 0)>>ip_output.txt
  13. )
  14. pause
复制代码
ip_tmpok.txt文本片段
  1. 77.234.90.140 12712 *.googlevideo.com gvs 1.0
  2. 150.100.16.94 12821 *.googlevideo.com
  3. 109.245.221.47 13253 *.googlevideo.com
  4. 61.238.239.209 NA_183 *.googlevideo.com gvs 1.0
  5. 106.103.1.156 NA_239 *.googlevideo.com gvs 1.0
  6. 172.217.26.155 NA_239 *.google.com gws
  7. 172.217.26.138 NA_246 *.googleapis.com gws
复制代码
问题点:
代码运行时,直接一闪而过,没有输出具体内容。
去掉if 语句,批处理能输出内容。
因此怀疑是 if 中的括号的问题。但对 if 中的括号用 ^ 进行转义也没效果(对'(' 和 ')' 分别转义,各种组合都试了下,如只转义一个')',转义全部')'等,但都不行。)
这个代码怎么改?
还有,这种嵌套括号,是不是都是靠转义来处理的?
作者: pcl_test    时间: 2016-9-25 09:11

建议先把基础学好
if "!tp:~0,3!"=="NA_"
作者: idos    时间: 2016-9-25 09:37

if语句少加了双引号,应为:if "!tp:~0,3!"=="NA_"
多看看教程:http://www.bathome.net/viewthread.php?tid=2530&highlight=if
作者: sishentibu    时间: 2016-9-25 09:41

回复 2# pcl_test

是字符串啊。有段时间没接触批处理了,看到这个
  1. IF [NOT] string1==string2 command
复制代码
完全没反应过来要加"".
谢谢了
作者: sishentibu    时间: 2016-9-25 09:43

回复 3# idos


    有学习过的,然而有段时间不用,忘记了
作者: cutebe    时间: 2016-9-25 09:54

如果不加双引号,实际要转义的是字符串截取 !tp:~0,3! 中的逗号
作者: sishentibu    时间: 2016-9-25 11:06

回复 6# cutebe


    ,不是普通的字符吗?为什么会需要转义?
作者: GNU    时间: 2016-9-26 22:07

回复 7# sishentibu


逗号在某些情况下是作为命令分隔符之一进行处理的,比如这个教程里面第25页提到的例子:
http://bbs.bathome.net/thread-31727-1-1.html
作者: sishentibu    时间: 2016-9-27 18:38

回复 8# GNU


    查了下,真是特殊字符,一直没注意。。




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2