问题
I have a text file and would like to extract all the lines between two specified lines using windows batch scripting.
Line1: !FILE_FORMAT=ADS
Line2: !VERSION=1.0
.
.
LineX: 'Parent|Child|IsPrimary|**** (the line starts with ' and is long)
.
.
LineY: !PropertyArray=Cost Center (The lines starts with !)
.
.
LineZ.
I want to extract all the lines between LineX and LineY and output it to another file.
The below code finds the starting line correctly. But it just deletes the line(Line Y) where I want the stop the script and outputs the rest of the file.
The output is from Line X to Line Z without Line Y.
@for /f "tokens=1 delims=[]" %%a in ('find /n "'Parent|Child"^<D:\DEV\Test\Cost_Center.txt') do @(
more +%%a D:\DEV\Test\Cost_Center.txt |find /v "!PropertyArray=Cost Center" || goto :eof)>D:\DEV\Test\Cost_Center_Out.txt
回答1:
you can do this with sed for Windows:
sed "/'Parent|Child|IsPrimary|/,/!PropertyArray=Cost Center/!d" file1 > file2
回答2:
@ECHO OFF
SETLOCAL
SET "sourcedir=c:\sourcedir"
SET "destdir=c:\destdir"
for /f "tokens=1 delims=[]" %%a in ('find /n "'Parent|Child"^<"%sourcedir%\Cost_Center.txt" ') do set /a start=%%a
for /f "tokens=1 delims=[]" %%a in ('find /n "!PropertyArray=Cost Center"^<"%sourcedir%\Cost_Center.txt" ') do set /a end=%%a
(
for /f "tokens=1* delims=[]" %%a in ('find /n /v ""^<"%sourcedir%\Cost_Center.txt" ') do (
IF %%a geq %start% IF %%a leq %end% ECHO(%%b
)
)>"%destdir%\newfile.txt"
GOTO :EOF
Using the approach that you're comfortable with - I've changed the source and destination directories/filenames to suit my system. Not sure whether you want to include your two target lines - it's just a matter of changing geq
to gtr
and/or leq
to lss
depending on which, if any, you want to exclude.
Might have been easier if you'd included some sample data...
edit 20130807T0207Z ECHO
becomes ECHO(
to cope with empty lines.
回答3:
This uses a helper batch file called findrepl.bat
from - http://www.dostips.com/forum/viewtopic.php?f=3&t=4697
type file.txt |findrepl "^'Parent\|Child\|IsPrimary\|" /e:"^!PropertyArray=Cost" |findrepl /v "^!PropertyArray=Cost">newfile.txt
The ^
at the start of the terms means it starts in column one. The \|
you see is the escaping of the |
character.
来源:https://stackoverflow.com/questions/18069790/batch-script-to-extract-lines-between-two-specified-lines