Using CMD read text file line by line and copy to another file with some changes

75 Views Asked by At

I am using the following batch script to read a text file line by line, make some changes line based on certain conditions, and output the result to a new file.

@echo off
set source=mysourcefile.txt

type NUL > new_%source%

FOR /f "usebackq delims=" %%b IN (".\%source%") DO (
 REM make some changes to the line and output the result to the new file
 set "outline=%%b"
 REM echo %outline% >> new_%source%
 echo %outline%>>new_%source%
)

The problem is when I use the compare tool to compare the old and the new file, I see the line endings are different, and the new file has an extra space at the end of each line.

How to fix this problem?

Update: I fixed the echo statement to remove the spaces. However, I noticed that the empty lines are not created in the new file. How to solve this problem?

1

There are 1 best solutions below

2
tarekahf On

The following script will fix the problem:

@echo off
set source=mysourcefile.txt

type NUL > new_%source%

FOR /f "delims=" %%l IN ('findstr /N "^" ".\%source%"') DO (
 set "line=%%l"
 set "line=!line:*:=!"
 echo(!line!>>new_%source%
)

We need to prefix the output with the line number using the "findstr" command, then, remove the line number from the output including the column.