假设你的意思是abc 24 xyz
. (最简答案在底部)
这为您提供了最大的灵活性和最清晰的变量。
@echo off
setlocal enabledelayedexpansion
:: Just making sure that %data% is empty
set data=
for /f "tokens=1,2* delims==" %%x in (a.txt) do call :work %%x "%%y"
:: Removes leading space and sends to b.txt
echo %data:~1%>b.txt
goto :eof
:work
set var=%1
set val=%~2
:: Remove any leading spaces.
:work-loop
if "!val:~0,1!"==" " (
set val=!val:~1!
goto :work-loop
)
if "%var%"=="name" set data=%data% %var%
if "%var%"=="age" set data=%data% %var%
if "%var%"=="country" set data=%data% %var%
goto :eof
或者短一点。
@echo off
setlocal enabledelayedexpansion
set data=
for /f "tokens=1,2* delims==" %%x in (a.txt) do call :work %%x "%%y"
:: Removes leading space and sends to b.txt
echo %data:~1%>b.txt
echo %data%>b.txt
goto :eof
:work
set var=%1
set val=%~2
:since leading spaces have not been removed, there need be no space between %data% and %var%
if "%var%"=="name" set data=%data%%var%
if "%var%"=="age" set data=%data%%var%
if "%var%"=="country" set data=%data%%var%
goto :eof
最短的答案
@echo off
setlocal
for /f "tokens=1,2* delims== " %%x in (a.txt) do (
if "%%x"=="name" set %%x=%%y
if "%%x"=="age" set %%x=%%y
if "%%x"=="country" set %%x=%%y
)
echo %name% %age% %country%>b.txt
endlocal
在最后一个中,使用setlocal
and endlocal
are not ness :: 删除前导空格并发送到 b.txt echo %data:~1%>b.txt iary,它们只是确保您的变量在批处理文件结束时消失。