批处理,从文本文件中获取数字并将其写入变量

Batch, Get number from text file and write it as a variable

我想做的是从 .txt 文件中获取一个 number 并将其设为变量。

例如,MyFile.txt包含数字“2”,我需要将数字“2”设为变量。

for /F "delims=" %%x in ("%USERPROFILE%\MyFile.txt") do set myVar=%%x

我怎样才能做到这一点?

集合列表中的双引号用于处理字符串。要么完全摆脱它们,要么(如果你需要它们,因为 %USERPROFILE% 包含空格),添加 usebackq 选项。

来自for /?的输出:

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

    or, if usebackq option present:

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]

所以在你的情况下,要么是

for /F "delims=" %%x in (%USERPROFILE%\MyFile.txt) do set myVar=%%x

for /F "usebackq delims=" %%x in ("%USERPROFILE%\MyFile.txt") do set myVar=%%x

但是这两者都假设 MyFile.txt 中只有一行;否则 myVar 将被设置为文件的最后一行。