cmd - Batch Files: How to concatenate each line in a text file? -
i have text file text on each line. able put each line in 1 long line along space. so, if text file has:
bob jack sam i want result
bob jack sam below 2 methods working on stuck. in brackets [] means know syntax wrong; put there show thought process. commented sections me experimenting , have left them in case wants comment on / why do.
method 1:
@echo off setlocal enabledelayedexpansion set count=1 /f "tokens=* delims= usebackq" %%x in ("afile.txt") ( set var!count!=%%x %%a in (!count!) ( !var%%a! = !var%%a! & " " echo !var%%a! ) set /a count=!count!+1 echo !count! ) ::echo !var1! !var2! !var3! start "" firefox.exe !var%%a!-1 endlocal ::echo "endlocal" %var1% %var2% %var3% method 2:
@echo off setlocal enabledelayedexpansion set count=1 /f "tokens=* delims= usebackq" %%x in ("afile.txt") ( set var!count!=%%x call echo %%var!count!%% set /a count=!count!+1 echo !count! ) ::echo !var1! !var2! !var3! start "" firefox.exe ^ [i = 1] [for !count! (] call echo %%var!count!%% & " " & " "^ endlocal ::echo "endlocal" %var1% %var2% %var3%
if have 3 values, can directly retrieve them file
< input.txt ( set /p "line1=" set /p "line2=" set /p "line3=" ) set "var=%line1% %line2% %line3%" echo("%var%" if don't know number of values, use for /f command read lines , concatenate contents variable.
@echo off setlocal enableextensions enabledelayedexpansion set "var=" /f "usebackq delims=" %%a in ("input.txt") set "var=!var!%%a " echo("%var%" but if data can contain exclamation signs, delayed expansion state remove them (and text surounded them). avoid it, can used
@echo off setlocal enableextensions disabledelayedexpansion set "var=" /f "usebackq delims=" %%a in ("input.txt") ( setlocal enabledelayedexpansion /f "tokens=* delims=¬" %%b in ("¬!var!") endlocal & set "var=%%b%%a " ) echo("%var%" where setlocal/endlocal , inner for used avoid problems ! character
or can try this
@echo off setlocal enableextensions disabledelayedexpansion /f "delims=" %%a in (' "<nul cmd /q /c "for /f "usebackq delims=" %%z in ("input.txt"^) (set /p ".=%%z "^)"" ') set "var=%%a" echo("%var%" it runs cmd instance output input lines 1 output line (<nul set /p used ouput data without line feeds, data in same line). wrapped in for retrieve output inside variable
Comments
Post a Comment