读取多行文本文件并在批处理文件中分配多个命名的环境变量

读取多行文本文件并在批处理文件中分配多个命名的环境变量

我正在尝试读取多行文本文件,例如......

测试文件.txt

文本文件包含:

bof --------------------------------
This is line 1
  This is line 2
C:\util 
This is line 4
EOF --------------------------------

我可以逐行阅读并使用以下命令回显它们:

@For /F Tokens^=1*Delims^=]^ EOL^= %%A In ('Find /N /V ""^<"C:\test.txt"') Do @Echo(%%B&>Nul echo

我想在循环过程中设置环境变量,因此我需要在循环内部动态地命名它们并分配值。

对于我的目的来说,实际上并不需要回显屏幕,只需要完成作业即可。

获取文本行后,如何才能执行以下操作?

Echo _var1=%_var1%
echo _var2=%_var2%
echo _var3=%_var3%
echo _var4=%_var4%

谢谢

答案1

您可以在此处使用延迟扩展:

@echo off & setlocal enableDelayedExpansion & set i=0
@For /F "Tokens=1* Delims=] EOL=" %%A In ('Find /N /V ""^<"C:\test.txt"') Do (
   set /a i=i+1
   set "_var!i!=%%B"
)

现在这里:

For /l %%a in (1,1,4) do echo _var%%a is !var%%a!

会给:

_var1 is This is line 1
_var2 is   This is line 2
_var3 is C:\util
_var4 is This is line 4

阅读更多:

答案2

@echo off

cd /d "%~dp0" && setlocal EnableDelayedExpansion

for /f ^tokens^=*delims^= %%i in ('type test.txt'
)do set /a "_c+=1+0" && <con: set "_var!_c!=%%~i"

for /l %%l in (1 1 !_c!)do echo\_var%%l=!_var%%l!

%__AppDir__%timeout.exe -1 & endlocal & goto=:EOF

  • test.txt文件内容/布局:
This is line 1
  This is line 2
C:\dir
This is line 4
This is line 5
C:\util
This is line 7
C:\folder
This is line 9

  • 输出:
_var1=This is line 1
_var2=  This is line 2
_var3=C:\dir
_var4=This is line 4
_var5=This is line 5
_var6=C:\util
_var7=This is line 7
_var8=C:\folder
_var9=This is line 9

1.您不需要使用将行上的所有字符串保存/设置为变量,因此没有必要,请使用"Tokens=1* Delims=] EOL="tokens^=*delims^=,这将标记设置为全部并重置/删除默认分隔符。

... for /f ^tokens^=*delims^= %%i in (test.txt) ...

2.增加行数计数器,以便您可以for /L动态地使用循环,而无需编辑它来手动添加文件中的行数。

... set /a "_c+=1+0" ...

观察:使用时+=1+0set /a "_c+=1+0",你不需要用set _c=0

3.使用运算符在计数器递增后立即设置变量,方法是使用已递增的计数器存储当前行

... set /a "_c+=1+0" && <con: set "_var!_c!=%%~i" ...

4.要动态列出已保存的变量/行,请将其用作循环的限制for /L变量中已保存的总数!_C!,要选择它们,只需进行连接操作_var + %%l

for /l %%l in (1 1 !_c!)do echo\_var%%l=!_var%%l!

观察:5如果行中的第一个字符是spacetab并且您需要删除它,只需删除分隔符:

for /f ^tokens^=*delims^= %%i in ('type test.txt')do ...

@echo off && setlocal EnableDelayedExpansion

cd/d "%~dp0" && for /f tokens^=* %%i in (file.txt
)do set /a "_c+=1+0" && <con: set "_var!_c!=%%~i"

for /l %%l in (1 1 !_c!)do echo\_var%%l=!_var%%l!

%__AppDir__%timeout.exe -1 & endlocal & goto=:EOF

  • file.txt文件内容/布局:
This is line 1
TabThis is line 2
C:\dir
This is line 4
This is line 5
SpaceC:\util
This is line 7
C:\folder
This is line 9

  • 如果第一个字符与标准分隔符相同,则输出从行中删除第一个字符:
_var1=This is line 1
_var2=This is line 2
_var3=C:\dir
_var4=This is line 4
_var5=This is line 5
_var6=C:\util
_var7=This is line 7
_var8=C:\folder
_var9=This is line 9

相关内容