ysrini
February 8, 2013, 12:01pm
1
Hi,
I have text file like the following:
Start
a
b
121
c
d
End
Start
a
31
e
f
End
Start
p
o
i
k
l
993
End
Now I want to output the Start-End block that contains my search string
So if I search for '121' it should output the first block, search for 'k' then output the last block
Thanks,
-sri
Yoda
February 8, 2013, 12:21pm
2
awk -v V="121" ' /Start/ {
s=x;
s=$0;
} !/Start/&&!/End/ {
s=s RS $0;
} $0 == V {
f = 1;
} /End/ && f == 1 {
s=s RS $0;
print s;
f = 0;
}' file
ysrini
February 8, 2013, 12:25pm
3
Got the solution
awk '/Start/{s=x}{s=s$0"\n"}/121/{p=1}/End/ && p{print s;exit}' <filename>
Jotne
February 8, 2013, 12:25pm
4
Converting it each section to rows, simplify handling it.
awk '{if ($0~"End") {print $0"\n"} else {print $0","}}' ORS="" | awk '/k/'
Start,p,o,i,k,l,993,End
Yoda
February 8, 2013, 12:30pm
5
Note that this program will not print another section if the search pattern is repeated. But if that is what you want, then it is OK.
ysrini
February 8, 2013, 1:24pm
6
Hi bipinajith, the search string will not appear in multiple blocks, thanks for thinking about this.
After I posted my question I found solution based on the following link (credit goes to this):