Saving a batch variable in a text file

情到浓时终转凉″ 提交于 2019-12-18 05:00:30

问题


I am trying to save a batch variable into a text file. I currently have this code:

@echo off

Set var=6
@echo %var%>txt.txt

For /f "tokens*" %%i in (txt.txt) do @echo %%i
Pause

It's supposed to save the 6 into the variable var and then write the variable in a text file. I want to do this to save user input into a text file so that when the batch program is terminated it will hold the variables.


回答1:


There is a little problem with redirection. You are redirecting a "stream"; they are numbered 0-9. 0 is for "Standard Input" (STDIN), 1 is for "Standard Output" (STDOUT), 2 is for "Error Output" (STDERR).

If you use the redirection symbol > without a stream number, it defaults to "1".

So echo text>txt.txt is just an abreviation for echo text 1>txt.txt

Now it's getting tricky: echo 6>txt.txt won't echo "6" to the file, but tries to redirect "Stream 6" (which is empty) to the file. The Standard Output echo is off goes to the screen, because "Stream1" is not redirected.

Solution:

If you try to redirect a number or a string which ends with a number, just use a different syntax:

>txt.txt echo 6



回答2:


Use the set command to get the contents of a file:

set /p var=<filename

Use the echo command to put into a file:

@echo Contents Of File > "FileName"

To append another line to the end of the file, use:

@echo Contents Of File >> "FileName"

Also, put the commands on separate lines or use '&&' between them on the same line.



来源:https://stackoverflow.com/questions/28133052/saving-a-batch-variable-in-a-text-file

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