Keeping blank lines intact when reading from one f

2019-08-06 17:00发布

问题:

I am reading line by line from a properties file to another file using below code(batch file). The problem is It is removing all the blank lines from the source file. What changes I should do in order to make blank lines available to destination file?

FOR /F "USEBACKQ tokens=*" %%A IN (`FIND /V "" ^<"%FILE%.SRC"`) DO (
  ECHO %%A>>"%FILE%"
)

回答1:

FOR /F will always skip empty lines, so you have to avoid empty lines.

This can be solved with prepending the lines by a line number with findstr or find.

Then you only need to remove the line number.

(
  setlocal DisableDelayedExpansion
  for /F "delims=" %%L in ('findstr /n "^" "%FILE%.src"') do (
    set "line=%%L"
    setlocal EnableDelayedExpansion
    set "line=!line:*:=!"
    echo(!line!
    endlocal
  )
) > "%FILE%"

The toggling of the delayed expansion mode is necessary, as you need delayed expansion for removing the line number up to the first colon.
But you need disabled expansion for tranfering the %%L to the line variable, else it would destroy exclamation marks and sometimes carets.

The set/p technic to read a file is a different approach, described at SO:Batch files: How to read a file?