当几个命令被括在括号中,并且有重定向文件到整个块:
< input.txt (
command1
command2
. . .
) > output.txt
... 然后,只要块中的命令处于活动状态,文件就保持打开状态,因此这些命令可能会移动重定向文件的文件指针。MORE和FIND命令在处理Stdin文件之前都将Stdin文件指针移动到文件的开头,因此同一个文件可能在块中被处理多次。例如,下面的代码:
more < input.txt > output.txt
more < input.txt >> output.txt
... 产生与此相同的结果:
< input.txt (
more
more
) > output.txt
这段代码:
find "search string" < input.txt > matchedLines.txt
find /V "search string" < input.txt > unmatchedLines.txt
... 产生与此相同的结果:
< input.txt (
find "search string" > matchedLines.txt
find /V "search string" > unmatchedLines.txt
)
FINDSTR则不同;它不会将Stdin文件指针从当前位置移动。例如,这段代码在搜索行之后插入新行:
call :ProcessFile < input.txt
goto :EOF
:ProcessFile
rem Read the next line from Stdin and copy it
set /P line=
echo %line%
rem Test if it is the search line
if "%line%" neq "search line" goto ProcessFile
rem Insert the new line at this point
echo New line
rem And copy the rest of lines
findstr "^"
exit /B
我们可以在辅助程序的帮助下很好地利用这个特性,该辅助程序允许我们移动重定向文件的文件指针,如本例所示。
这种行为最初是由jeb在这篇文章中报告的。
编辑2018-08-18:报告新的FINDSTR错误
FINDSTR命令有一个奇怪的错误,当这个命令用于显示字符的颜色,并且这样一个命令的输出被重定向到CON设备时发生。有关如何使用FINDSTR命令以颜色显示文本的详细信息,请参阅本主题。
When the output of this form of FINDSTR command is redirected to CON, something strange happens after the text is output in the desired color: all the text after it is output as "invisible" characters, although a more precise description is that the text is output as black text over black background. The original text will appear if you use COLOR command to reset the foreground and background colors of the entire screen. However, when the text is "invisible" we could execute a SET /P command, so all characters entered will not appear on the screen. This behavior may be used to enter passwords.
@echo off
setlocal
set /P "=_" < NUL > "Enter password"
findstr /A:1E /V "^$" "Enter password" NUL > CON
del "Enter password"
set /P "password="
cls
color 07
echo The password read is: "%password%"