批处理文件以将特定行从一个文本文件复制到另一文本文件 [英] Batch file to Copy particular lines from one text file to another text file

查看:629
本文介绍了批处理文件以将特定行从一个文本文件复制到另一文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对批处理脚本非常陌生。我对批处理脚本了解不多。



我的疑问是如何仅将文本文件中的某些行复制到其他文本文件中。



说我的File.txt是

 这是示例文件。 
我要复制此行。
也是这一行。
但不是这一行。

我想复制第2行和第3行,但不使用它们的行号,因为可能会更改。 / p>

这是我到目前为止所做的事情

  @ECHO OFF 
SET InFile = abc.txt
SET OutFile = Output.txt
IF EXIST%OutFile% DEL%OutFile%
SET TempFile = Temp.txt
IF存在%TempFile% DEL%TempFile%

如果存在%OutFile% DEL%OutFile%

FOR / F tokens = *% %A IN('FINDSTR我想要%InFile%')DO(
ECHO。%% A>%TempFile%
ECHO。%TempFile%>>%OutFile %
REM呼叫:RemovePrecedingWordA %% A

FOR / F tokens = * %% A IN('FINDSTR也是此%InFile%') DO(
ECHO。%% A>%TempFile%
ECHO。%TempFile%>>%OutFile%
REM CALL:RemovePrecedingWordA %% A

但它不起作用。请帮忙。

解决方案

您可以使用/ g:选项来查找str,基本上可以做到

  findstr /g:pattern.txt%InFile%> %OutFile%

其中pattern.txt是(在您的示例中)

 我要
还有

这假定您可以为要复制的所有行编写 findstr 正则表达式。



如果将findstr与多个文件(通配符)一起使用,您将获得前缀的文件名。为了解决这个问题,请使用

del out.txt
作为%F in(* .txt);执行findstr /g:pattern.txt%F>> out.txt

请注意,您应将源文件放在模式的不同目录中,然后输出文件(或使用其他扩展名),否则 *。txt 通配符也会提取这些文件。


I am very new to batch scripting. I don't have much knowledge about Batch Scripting.

My doubt is how to copy only some line from text file to other text file.

Say my File.txt is

This is sample file.
I want copy this line.
Also this line.
But not this line.

I want to copy line 2 and 3, but not using their line number, because may change.

This muchI have done till now:

@ECHO OFF
SET InFile=abc.txt
SET OutFile=Output.txt
IF EXIST "%OutFile%" DEL "%OutFile%"
SET TempFile=Temp.txt
IF EXIST "%TempFile%" DEL "%TempFile%"

IF EXIST "%OutFile%" DEL "%OutFile%"

FOR /F "tokens=*" %%A IN ('FINDSTR "I want" "%InFile%"') DO (
    ECHO.%%A> "%TempFile%"
    ECHO.%TempFile%>>"%OutFile%"
REM CALL :RemovePrecedingWordA "%%A"
    )
FOR /F "tokens=*" %%A IN ('FINDSTR " Also this" "%InFile%"') DO (
    ECHO.%%A> "%TempFile%"
    ECHO.%TempFile%>>"%OutFile%"
REM CALL :RemovePrecedingWordA "%%A"
    )

But its not working. Please help.

解决方案

You could use the /g: option to findstr, basically do

findstr /g:pattern.txt %InFile% > %OutFile%

where pattern.txt is (in your example)

I want
Also this

This assumes you can write findstr regular expressions for all the lines you want to copy.

If you use findstr with multiple files (wildcard) you will get the file name prepended. To get round this, use del out.txt for %F in (*.txt); do findstr /g:pattern.txt %F >> out.txt Note that you should put the source files in a different directory to the pattern and output files (or use a different extension) otherwise the *.txt wildcard will pick those files up, too.

这篇关于批处理文件以将特定行从一个文本文件复制到另一文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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