【发布时间】:2014-02-14 06:43:40
【问题描述】:
以下命令在 Windows Vista 和更早版本上无法正确运行。它在 Windows 7 及更高版本上运行良好。
BATCH 示例(命名为 whateveryouwanttocallit.cmd 或 somescript.bat(在这种情况下扩展名无关紧要)):
for /f "tokens=*" %%p in ('ping -n 1 127.0.0.1') do if not "%%p"=="" echo %%p
上面的脚本试图只显示非空行。
在 Windows 7 机器上,生成以下(正确)输出:
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
在 Windows Vista 和更早版本上,相同的脚本会产生不正确的输出:
ECHO is on.
Pinging 127.0.0.1 with 32 bytes of data:
ECHO is on.
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
ECHO is on.
Ping statistics for 127.0.0.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms
看起来早期的系统有额外的换行符。 早期系统是否有不同的输出格式?有没有办法以适用于早期和后期系统的方式完成此任务?解决方案越简单越好。
【问题讨论】:
-
在批处理文件中访问令牌时需要双
%...-> 使用%%p -
您还应该使用
"delims="来解析整行。 -
@npocmaka 我的错误,我应该澄清一下。该问题在 cmd 和批处理脚本中都存在
-
@foxidrive 或者
"tokens=*"。对手头的问题都没有影响 -
FWIW
"tokens=*"去除前导空格,因此解析文件名不可靠。最好始终使用分隔符。
标签: batch-file if-statement for-loop