请考虑以下两个循环:
for /f "tokens=*" %%a in ('dir /b %TEMP%') do (
echo %%a
)
和
for /f "delims=" %%a in ('dir /b %TEMP%') do (
echo %%a
)
如果我想要的结果是为变量%%a
提供要评估的整行内容,选项tokens=*
和delims=
在功能上是否等效?
在任何情况下,如果给定特定输入,我可能会得到另一个输出?
我想知道这两个选项是否应始终结合使用以保证涵盖所有潜在情况,或者同时指定这两个选项是否多余?
答案 0 :(得分:1)
是的,tokens=*
和delims=
不同:
delims=
返回未编辑的整行; tokens=*
返回删除任何前导定界符(默认为 SPACE 和 TAB )的行; tokens=* delims=
的行为与delims=
完全相同; 请注意,空行始终被跳过。另外,以;
开头的行也会被忽略,因为该字符是默认的eol
。
如果指定了tokens=*
,并且一行仅包含定界符,则for /F
循环将迭代,并且meta变量将返回一个空字符串。提供任何令牌编号后(例如tokens=3
,tokens=1,3
,tokens=2-3
,tokens=2*
等),将跳过仅分隔符的行。
但是,即使提供了eol
,也将忽略包含一个或多个定界符以及tokens=*
字符和任意字符串的行。
为证明起见,我使用以下文本文件sample.txt
做了一些测试(请注意,第2 nd 行为空,第4 th 行包含四个空格;单击此答案下方的edit按钮并查看原始文本):
text_without_delimiters text with delimiters text with leading and trailing delimiters ; comment text ; comment text with leading delimiters text plus ; comment text
这是我在控制台上所做的以及相应的返回字符串:
>>> for /F %I in (sample.txt) do @echo "%I"
"text_without_delimiters"
"text"
"text"
"text"
>>> for /F "tokens=*" %I in (sample.txt) do @echo "%I"
"text_without_delimiters"
"text with delimiters"
""
"text with leading and trailing delimiters "
"text plus ; comment text"
>>> for /F "delims=" %I in (sample.txt) do @echo "%I"
"text_without_delimiters"
"text with delimiters"
" "
" text with leading and trailing delimiters "
" ; comment text with leading delimiters"
"text plus ; comment text"
>>> for /F "tokens=* delims=" %I in (sample.txt) do @echo "%I"
"text_without_delimiters"
"text with delimiters"
" "
" text with leading and trailing delimiters "
" ; comment text with leading delimiters"
"text plus ; comment text"
>>> for /F "tokens=3" %I in (sample.txt) do @echo "%I"
"delimiters"
"leading"
";"
>>> for /F "tokens=1,3" %I in (sample.txt) do @echo "%I" "%J"
"text_without_delimiters" ""
"text" "delimiters"
"text" "leading"
"text" ";"
>>> for /F "tokens=2-3" %I in (sample.txt) do @echo "%I" "%J"
"with" "delimiters"
"with" "leading"
"plus" ";"
>>> for /F "tokens=2*" %I in (sample.txt) do @echo "%I" "%J"
"with" "delimiters"
"with" "leading and trailing delimiters "
"plus" "; comment text"
因此,唯一真正奇怪且出乎意料的输出是仅带有""
选项的行tokens=*
。