写Batch脚本跟写Perl的感觉差不多,都是可读性不好,但一旦了解语法,就觉得这门语言强大无比。文本处理啥的,效率嗖嗖的~
下文大部分内容摘录自国外网站的文章:
http://www.computing.net/howtos/show/batch-files-tokens-and-delimiters-for-loops/473.html <Batch Files: Tokens and Delimiters (FOR Loops)>
Tokens和Delimiters的作用
批处理脚本一般可以通过Tokens去找到变量的值,而Delimiters则是分割这些Tokens的间隔符。
比如有个bat文件,要读取MyFile.txt:
Hello World! How are you doing today?
现在我们想要程序输出World!这个单词,要怎么做呢?HOHO,理解下面的脚本了么?字符串是以空格为间隔的,所以delims=是空格,期望输出的单词是第二个token,所以tokens=2
FOR /f "tokens=2 delims= " %%a IN (MyFile.txt) DO ECHO %%a
输出某一范围的字符串
FOR /f 'tokens=3-7 delims= " %%a IN (MyFile.txt) DO ECHO %%a %%b %%c %%d %%e
结果: How are you doing today?
FOR /f 'tokens=1, 3, 6 delims= " %%a IN (MyFile.txt) DO ECHO %%a%%b %%c
结果: Hello How doing
输出整行
FOR /f "tokens=* delims= " %%a IN (MyFile.txt) DO ECHO %%a
另一个例子
假设MyFile.txt的内容是:Hello World! /How are you today?/
那么,FOR /f "tokens=2 delims=/" %%a IN (MyFile.txt) DO ECHO %%a
应该输出:How are you today?