Here is a pure batch-file solution:
The following code snippet removes the last character from each line in file.txt
if it is ,
and writes the result into file_new.txt
:
@echo off
setlocal EnableExtensions
> "file_new.txt" (
for /F usebackq^ delims^=^ eol^= %%L in ("file.txt") do (
setlocal DisableDelayedExpansion
set "LINE=%%L"
setlocal EnableDelayedExpansion
if "!LINE:~-1!"=="," (
echo(!LINE:~,-1!
) else (
echo(!LINE!
)
endlocal
endlocal
)
)
endlocal
The toggling of delayed environment variable expansion (see setlocal /?
and set /?
for help) is required to avoid trouble with some special characters.
The above approach removes empty lines from the file as for /F
ignores them. To avoid this, use the following script:
@echo off
setlocal EnableExtensions
> "file_new.txt" (
for /F delims^=^ eol^= %%L in ('findstr /N /R "^" "file.txt"') do (
setlocal DisableDelayedExpansion
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "LINE=!LINE:*:=!"
if "!LINE:~-1!"=="," (
echo(!LINE:~,-1!
) else (
echo(!LINE!
)
endlocal
endlocal
)
)
endlocal
This uses the fact that findstr /N /R "^"
returns every line (even empty ones) of the given file and prefixes it with a line number plus :
. Therefore no line appears to be empty to for /F
. The line set "LINE=!LINE:*:=!"
is inserted to remove that prefix (everything up to the first :
) from each line prior to outputting.