如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
当前回答
dir 1 > a . txt 2 > &1 |式a . txt。
这将有助于重定向STDOUT和STDERR
其他回答
如果你在CLI中,为什么不用FOR循环来“DO”你想做的事情:
for /F "delims=" %a in ('dir') do @echo %a && echo %a >> output.txt
Great resource on Windows CMD for loops: https://ss64.com/nt/for_cmd.html The key here is setting the delimeters (delims), that would break up each line of output, to nothing. This way it won't break on the default of white-space. The %a is an arbitrary letter, but it is used in the "do" section to, well... do something with the characters that were parsed at each line. In this case we can use the ampersands (&&) to execute the 2nd echo command to create-or-append (>>) to a file of our choosing. Safer to keep this order of DO commands in case there's an issue writing the file, we'll at least get the echo to the console first. The at sign (@) in front of the first echo suppresses the console from showing the echo-command itself, and instead just displays the result of the command which is to display the characters in %a. Otherwise you'd see:
echo驱动器[x]中的卷为Windows
UPDATE: /F跳过空行,唯一的修复是预过滤输出,向每一行添加一个字符(可能通过命令find使用行号)。在CLI中解决这个问题既不快速也不漂亮。此外,我没有包括STDERR,所以这里捕获错误:
for /F "delims=" %a in ('dir 2^>^&1') do @echo %a & echo %a >> output.txt
重定向错误消息
插入符号(^)用于转义后面的符号,因为命令是一个正在被解释的字符串,而不是直接在命令行中输入它。
这是可行的,尽管它有点丑陋:
dir >_ && type _ && type _ > a.txt
它比其他一些解决方案更灵活一些,因为它是一条一条地工作的,所以您也可以使用它来追加。我在批处理文件中经常使用这种方法来记录和显示消息:
ECHO Print line to screen and log to file. >_ && type _ && type _ >> logfile.txt
是的,您可以只重复ECHO语句(一次用于屏幕,第二次重定向到日志文件),但这看起来同样糟糕,并且存在一些维护问题。至少这样您就不必在两个地方对消息进行更改。
注意_只是一个简短的文件名,所以你需要确保在批处理文件的末尾删除它(如果你使用的是批处理文件)。
我能够找到一个解决方案/工作区重定向输出到一个文件,然后到控制台:
dir > a.txt | type a.txt
其中dir是需要重定向输出的命令,a.txt是存储输出的文件。
如果你想在屏幕上真正看到一些东西,下面的步骤会有所帮助——即使批处理文件被重定向到一个文件。如果重定向到一个文件,也可以使用设备CON
例子:
ECHO first line on normal stdout. maybe redirected
ECHO second line on normal stdout again. maybe redirected
ECHO third line is to ask the user. not redirected >CON
ECHO fourth line on normal stdout again. maybe redirected
另请参阅良好的重定向说明:http://www.p-dd.com/chapter7-page14.html
I agree with Brian Rasmussen, the unxutils port is the easiest way to do this. In the Batch Files section of his Scripting Pages Rob van der Woude provides a wealth of information on the use MS-DOS and CMD commands. I thought he might have a native solution to your problem and after digging around there I found TEE.BAT, which appears to be just that, an MS-DOS batch language implementation of tee. It is a pretty complex-looking batch file and my inclination would still be to use the unxutils port.