With Windows batch file, how to parse a file and output part to one file, part to another?

不问归期 提交于 2020-01-24 19:50:13

问题


I'm a Perl programmer, but I need to do a Windows batch file for a particular task.

The script needs to read an input file line by line, and copy to an output file. However part way through, it needs to switch output files.

For reading an input file and outputing to a file generally, the solution in the following article by Jeb seems to work best. (Other solutions don't work well when the input data has weird characters or long lines) Batch files: How to read a file?

However I can't get it to work where I change the outputfile mid-way. The problem is probably with the way DelayedExpansion works.

When I run the following script, outfile at the end is still a.txt, and new_variable is not set.

@echo off
del /f/q a.txt
del /f/q b.txt
del /f/q c.txt
del /f/q out.txt

set outfile=a.txt
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ in.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    IF "!%var!" == "/************************** PLUGINS SECTION *************************/" (
   set outfile=b.txt
   set new_variable=this
   echo "FOUND! Value of outfile should change to b.txt"
  )
  echo( !outfile! !var! >>!outfile!
    ENDLOCAL
)

echo Outfile:      %outfile%
echo New Variable: %new_variable%

回答1:


You loose your variable changes after the endlocal.
So you need to save the values over the endlocal barrier.
The easiest way here is to use the FOR-Endlocal technic.

 SETLOCAL DisableDelayedExpansion
 FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ in.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    if "!var!" == "****" (
      set outfile=b.txt
      set new_variable=this
    )
  FOR /F "tokens=1,2" %%O in (!outfile! !new_variable!) DO
  (
    ENDLOCAL
    set "outfile=%%O"
    set new_variable=%%P
  )
)

This works as the %%O and %%P parameters of the FOR-loop are not affected by the ENDLOCAL.
Both values are cached over the barrier.



来源:https://stackoverflow.com/questions/11408295/with-windows-batch-file-how-to-parse-a-file-and-output-part-to-one-file-part-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!