在包含不同字符(例如“”)的文件中写入整个cmd命令。或“ >>" [英] Writing a whole cmd command in a file that contains different characters,such as ">" or " >>"
问题描述
我想将此代码写入文件名为final.txt的文件中:
I want to write this code in a file with file name final.txt:
@echo off dir file1.txt > file2.txt
我已经尝试过这样的事情:
I've tried something like this :
"@echo off dir file1.txt > file2.txt"
但是它只写
"@echo off dir file1.txt > "
它不会复制整个命令,也将复制反逗号。
It doesn't copy the whole command and the inverted commas are copied too.
推荐答案
某些字符具有特殊含义,会被执行而不是回显。 >
是其中之一。要回显它们,必须转义它们(使用另一个特殊字符,即插入号 ^
)。另外,要在一行中执行两个命令,还必须用&
(其中的另一个特殊字符)将它们分开。最后,要执行最终文件,其扩展名必须为 .bat
或 .cmd
。并且您需要另一个 echo
来回显 @echo ...
:
Some chars have a special meaning and gets executed instead of echoed. >
is one of them. to echo them, you must "escape" them (with another special char, the caret ^
). Also to execute two commands in one line, you have to separate them with &
(another one of those special chars). And last not least, to be able to execute the final file, it's extension has to be .bat
or .cmd
. And you need another echo
to echo the @echo ...
:
echo @echo off & dir file1.txt ^> file2.txt > final.bat
但是 final.bat
如果您将每一行写在自己的行上,则可读性更好:
But final.bat
would be better readable, if you write every line on its own line:
echo @echo off>final.txt
echo dir file1.txt ^>file2.txt >>final.bat
(>>
用于附加到文件而不是覆盖文件)
(>>
is used to append to a file instead of overwriting it)
仅提及: echo
不是唯一可以通过 @
静默的命令。具有相同效果的较短代码:
just to mention: echo
is not the only command that can be quieted with @
. Shorter code with same effect:
echo @dir file1.txt^>file2.txt>>final.bat
这篇关于在包含不同字符(例如“”)的文件中写入整个cmd命令。或“ >>"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!