How to echo “2” (no quotes) to a file, from a batch script?

China☆狼群 提交于 2020-04-05 07:52:06

问题


How do I echo the number 2 into a file, from a batch script?

This doesn't work:

Echo 2>> file.txt

because 2>> is a special command. :(


回答1:


Use (ECHO 2)>>file.txt. This will output 2 without any spaces.




回答2:


Little-known feature: The redirection operator can go anywhere on the line.

>>file.txt echo 2



回答3:


echo ^2>>file.txt appears to work for me.




回答4:


Use the ^ escape :

Echo ^2>> file.txt



回答5:


echo.2>>text.txt

Yes, it's weird.




回答6:


another method

echo>>file.txt 2



回答7:


Or you can use the delayed expansion

setlocal EnableDelayedExpansion
set "var=2"
echo(!var!>> file.txt



回答8:


If you need an accurate write, use this command

(ECHO |set /p=2)>>file.txt

the command by DMan will produce a 0x0D0A line break behind the "2"




回答9:


To write a number to a file without a trailing line-break you could use the following:

cmd /C set /A "2">file.txt

This works, because set /A returns the (last) result (without line-break) when executed in command prompt context (hence when directly run in cmd.exe).

If you are working in command prompt anyway, you could simply use this:

set /A "2">file.txt

Though you cannot use that in a batch file, you need the extra cmd /C to force the right execution context.

Needless to say, this can of course only output numbers, or precisely said, signed 32-bit integers.




回答10:


Based on this answer, if anyone is wondering how to do this:

echo "command1 && command2" > file.txt

with no qoutes in file.txt then you do it like this:

echo command1 ^&^& command2 > file.txt

Tested on Windows Server 2003.




回答11:


escape the haracter '2'

in linux: echo \2>file.txt

in windows: echo ^2>file.txt

in windows this also will work

echo.2>file.txt no space between echo and the dot



来源:https://stackoverflow.com/questions/7225630/how-to-echo-2-no-quotes-to-a-file-from-a-batch-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!