batch script to extract lines between two specified lines

别说谁变了你拦得住时间么 提交于 2020-01-05 19:44:50

问题


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

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