How to grep for searching a string within a begin and end pattern of a file.
Sent from my Redmi 3S using Tapatalk
How to grep for searching a string within a begin and end pattern of a file.
Sent from my Redmi 3S using Tapatalk
awk '/STARTREGEX/ { P=1 } ; /ENDREGEX/ { P=0 } ; P && /LINEREGEX/' datafile
If that doesn't work we will need a LOT more details.
Thank you for the help.
However, I wanted to fetch the first line after the 'STARTREGEX' as well, as each pattern block name(1st line after the pattern) containing the matched string is also required.
I missed to mention the above prior !
E.g.:
START
Block1
..
..
string
..
END
START
Block2
..
..
END
START
Block3
..
string
..
END
So, here I wanted the output like:
Block1 string
Block3 string
Awaiting your suggestions..!
Given the code that Corona688 suggested, can you show us how you might be able to modify that suggestion to get the output you want.
I tried the below code :
awk '/STARTREGEX/{P=1;getline;print;} ; /ENDREGEX/ { P=0 } ; P && /LINEREGEX/{ print }' datafile
This however prints all the block names along with the lines where the string is matched.
Block1 string
Block2
Block3 string
How about
awk '/^Block/ {BL = $0} /START/,/END/ {if (/string/) print BL, $0}' file
Block1 string
Block3 string
---------- Post updated at 11:58 AM ---------- Previous update was at 11:36 AM ----------
Thank you RudiC for the alternate solution,
However the word Block was to illustrate an example, the file actually has different block names and only identifier is it is the next line after the STARTREGEX matched.
START
Block 1
..
string
..
END
START
Group 2
..
END
START
BLK 3
..
string
..
END
Result needed:
Block 1 string
BLK 3 string
Try
awk '/START/ {getline BL} /START/,/END/ {if (/string/) print BL, $0}' file
Thank you..I tried it and it works as expected!