[英]Batch file to Copy particular lines from one text file to another text file
我是批處理腳本的新手。 我對Batch Scripting知之甚少。
我懷疑的是如何只將一些行從文本文件復制到其他文本文件。
說我的File.txt是
This is sample file.
I want copy this line.
Also this line.
But not this line.
我想復制第2行和第3行,但不使用它們的行號,因為可能會改變。
我到目前為止做的很多:
@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"
)
但它不起作用。 請幫忙。
你可以使用/ g:選項來findtr,基本上可以
findstr /g:pattern.txt %InFile% > %OutFile%
其中pattern.txt是(在你的例子中)
I want
Also this
這假設您可以為要復制的所有行編寫findstr
正則表達式。
如果您將findstr與多個文件(通配符)一起使用,則會獲得前置文件名。 為了解決這個問題,請del out.txt for %F in (*.txt); do findstr /g:pattern.txt %F >> out.txt
使用del out.txt for %F in (*.txt); do findstr /g:pattern.txt %F >> out.txt
del out.txt for %F in (*.txt); do findstr /g:pattern.txt %F >> out.txt
請注意,您應該將源文件放在模式和輸出文件的不同目錄中(或使用不同的擴展名),否則*.txt
通配符將選擇這些文件也是。
您也可以將sed用於此目的。 某些行(在本例中為2和3)復制如下:
sed -n -e 2p -e 3p input.txt > output.txt
如果你想復制一段線(從第2行到第10行的所有行),你可以使用:
sed -n -e 2,10p input.txt > output.txt
或者您也可以使用某些行和段的組合:
sed -n -e 2,10p -e 15p -e 27p input.txt > output.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.