Writing a whole cmd command in a file that contain

2019-07-14 02:20发布

问题:

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" 

But it only writes

"@echo off dir file1.txt > "

It doesn't copy the whole command and the inverted commas are copied too.

回答1:

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

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)

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