Reputation: 53
In this case, I was able to remove the last character but in each of line using the ~0,-1!
As an example I want to diplay all the text from sample.txt
from
Hello World1
Hello World2
Hello World3
Hello World4
to
Hello World1,
Hello World2,
Hello World3,
Hello World4
To display this txt using my created batch file sample.bat
I'm using EnableDelayedExpansion
with For
loop
@setlocal enabledelayedexpansion
@echo off
for /f "delims=" %%i in ('type sample.txt') do (
set disp=%%i,
set disp=!disp:~0,-1!
echo !disp!
)
endlocal
However, the output still the same as sample.txt
Hello World1
Hello World2
Hello World3
Hello World4
Upvotes: 0
Views: 255
Reputation: 5874
Your issue is that you are adding the comma and immediately removing it before echoing. This leads to absolutely no change whatsoever as you experienced.
By commenting out that line we get closer to the desired output in your question:
@setlocal enabledelayedexpansion
@echo off
for /f "delims=" %%i in ('type sample.txt') do (
set disp=%%i,
REM set disp=!disp:~0,-1!
echo !disp!
)
endlocal
leads to:
Hello World1,
Hello World2,
Hello World3,
Hello World4,
which still is a comma too much (if that does not matter, you are set already with the commented line.
To get the last comma away I accepted that I get an empty line instead at the top of the output. As there is no short way of getting the amount of lines in a textfile except for counting in a loop before and the counting again to skip the setting of the comma in the output I decided to not echo
after but before every line. This will print the content of the variable in case there is another line in the file and else I have the modified (%%i,
) content in the variable for even more modifications:
@setlocal enabledelayedexpansion
@echo off
set disp=
for /f "delims=" %%i in ('type 01234.txt') do (
echo( !disp!
set disp=%%i,
)
set disp=!disp:~0,-1!
echo !disp!
endlocal
It is important to have any character immediately after the echo
((
and .
definitely work in this case). Like this there will no output if the content of the variable is empty. As you can see there is a final modification after the loop removing the comma of the last line before printing.
Upvotes: 1