Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines between two keywords

Tags:

linux

bash

sed

awk

Can someone suggest what to do if I have to read between two keywords like

*System_Power
1
1.2
1.8
2
*System_Terminate

In this case the asnwer would be

1
1.2
1.8
2

I tried using awk like

awk '$0 =="*System_Power"               #  start printing when 1st field is *System_Power
$0 != "*System_Terminate"{              #  until reach the  *System_Terminate
print;   } ' powerSummary > reportedFailure.k    # Read from file powerSummary and pipe to reportedFailure.k
exit

where the above data is found somewhere in the middle of file powerSummary.

I would be thankful for your corrections.

like image 338
hamad khan Avatar asked Feb 16 '12 16:02

hamad khan


2 Answers

This will work for you:

$ awk '/\*System_Power/{f=1;next}/\*System_Terminate/{f=0}f' infile
1
1.2
1.8
2
like image 96
SiegeX Avatar answered Sep 29 '22 23:09

SiegeX


You can use sed to trivially select the text between two matching lines, but this will also include the matching lines themselves...so we explicitly delete those:

sed -n '/System_Power/,/System_Terminate/ { 
    /^\*/ d
    p
}' < input

Awk can also select the text between matching lines:

awk '/System_Power/,/System_Terminate/ {print}' < input

...but like sed this will include the start/end terminators. You can fix this with awk, but I think you get a cleaner solution with sed.

like image 20
larsks Avatar answered Sep 29 '22 22:09

larsks