'How to display all line before and after string matches until blank line detected in shell
I need an help to grep a file which has lot of data. I have a file with below line:
random line with hashcode 1
This file is use for some analysis
Analysis code is <01234>
This is line after analysis
This is second test line
This file is use for some analysis
Analysis code is <01234>
This is line after analysis
Some data to be here as well
This file is use for some analysis
Analysis code is <01267>
This is line after analysis
I wanted to print only those line which have string "Analysis code" with value "01234" and print all line before and after it. I have tried to get the solution half way but need complete logic.
egrep -i "Analysis code" c.txt |
grep -i 01234 |
awk -F "<" '{print $2}' |
awk -F ">" '{print $1}' |
uniq > am.txt
while read line ; do
echo $line
awk "/$line/,/$^/" c.txt
done <am.txt
After this, I am getting output only starting from the line having the analysis code.
I wanted to print all lines before hho matching string as well until blank line appears on the top:
random line with hashcode 1
This file is use for some analysis
Analysis code is <01234>
This is line after analysis
This is second test line
This file is use for some analysis
Analysis code is <01234>
This is line after analysis
Solution 1:[1]
The easiest way is using grep option to print lines before and after matching line:
grep c.txt -e "Analysis code.*<01234>" -B1 -A2
If you want to print a paragraph that is separated by an empty line a multiline pattern can be used or awk like this:
awk -v RS='' '/Analysis code.*<01234>/' c.txt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
