使用Windows批处理文件,如何解析文件并将部分输出到一个文件,部分输出到另一个文件? [英] With Windows batch file, how to parse a file and output part to one file, part to another?

查看:66
本文介绍了使用Windows批处理文件,如何解析文件并将部分输出到一个文件,部分输出到另一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Perl程序员,但是我需要为特定任务制作Windows批处理文件.

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.

对于一般读取输入文件并输出到文件的情况,Jeb下一篇文章中的解决方案似乎效果最好.(当输入数据具有怪异字符或长行时,其他解决方案效果不佳)

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?

但是我无法在中途更改输出文件的地方使用它.问题可能出在DelayedExpansion的工作方式上.

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

当我运行以下脚本时,末尾的outfile仍然是a.txt,并且未设置new_variable.

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%

推荐答案

在endlocal之后放宽变量更改.
因此,您需要将值保存在 endlocal 屏障上.
这里最简单的方法是使用 FOR-Endlocal 技术.

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
  )
)

这是因为FOR循环的%% O和%% P参数不受 ENDLOCAL 的影响.
这两个值都在屏障上缓存.

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.

这篇关于使用Windows批处理文件,如何解析文件并将部分输出到一个文件,部分输出到另一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆