Sed to extract text between two lines

Please help me in using sed. I have a file as shown below.

START=A xxxxx xxxxx END START=A xxxxx xxxxx END START=A xxxxx xxxxx END START=B xxxxx xxxxx END START=A xxxxx xxxxx END START=C xxxxx xxxxx END START=A xxxxx xxxxx END START=D xxxxx xxxxx END 

I want to get text between START = A, END. I used the following query.

 sed '/^START=A/, / ^END/!d' input_file 

The problem here is, I get

 START=A xxxxx xxxxx END START=D xxxxx xxxxx END 

instead

 START=A xxxxx xxxxx END 
Sed finds it greedily.

Please help me in resolving this issue.

Thanks in advance.

Can AWK be used to achieve higher?

+7
source share
3 answers
 sed -n '/^START=A$/,/^END$/p' data 

The -n option means that it does not print by default; then the script says: "Print between the line containing START=A and the next END .

You can also do this with awk :

A pattern can consist of two patterns, separated by a comma; in this case, the action is performed for all lines from the occurrence of the first pattern, although the appearance of the second.

(from man awk on Mac OS X).

 awk '/^START=A$/,/^END$/ { print }' data 

Given the modified form of the data file in question:

 START=A xxx01 xxx02 END START=A xxx03 xxx04 END START=A xxx05 xxx06 END START=B xxx07 xxx08 END START=A xxx09 xxx10 END START=C xxx11 xxx12 END START=A xxx13 xxx14 END START=D xxx15 xxx16 END 

The output using GNU sed or Mac OS X (BSD) sed and using GNU awk or BSD awk is the same:

 START=A xxx01 xxx02 END START=A xxx03 xxx04 END START=A xxx05 xxx06 END START=A xxx09 xxx10 END START=A xxx13 xxx14 END 

Pay attention to how I changed the data file to make it easier to see where the various data blocks were printed in the file.

If you have another output requirement (for example, "only the first block between START = A and END" or "only the last ..."), then you need to clearly state this in the question.

+19
source

The basic version ...

 sed -n '/START=A/,/END/p' yourfile 

More reliable version ...

 sed -n '/^ *START=A *$/,/^ *END *$/p' yourfile 
+3
source

Your sed expression has a space to the end, i.e. / ^END/ . So sed gets the initial pattern, but doesn't get the final pattern and continues to print to the end. Use sed '/^START=A/, /^END/!d' input_file (notification /^END/ )

+2
source

All Articles