Sed and grep get line number to match

I have a log file and I use sed to extract lines between two lines that contain the word MATCH. I use sed to extract lines and grep only for lines containing the word "MATCH". I will need the line number in the log file where the match will be found.

Date:... TST STARTS DISCARD str1 DISCARD str2 MATCH str3 //line 5 MATCH str4 //line 6 DISCARD str5 TST FINISHED 

I use this command to extract the rows:

 sed -n "/TST STARTS/,/TST FINISHED/p" log.txt | grep "MATCHED". 

My conclusion:

 MATCH str3 MATCH str4 

But I also need to print the line number:

 line 5: MATCH str3 line 6: MATCH str4 
+8
bash grep sed
source share
3 answers

You can use:

 cat -n 

to type lines before applying your sed, for example:

 cat -n log.txt | sed -n "/TST STARTS/,/TST FINISHED/p" | grep "MATCHED" 

Alternatively, you can replace cat -n with the nl option:

 nl -n ln log.txt | sed ... 
+16
source share

My first attempt did not support line number because the sed part deletes certain lines.

Everything can be done with this awk :

 $ awk '/TST STARTS/ {p=1} p && /MATCH/ {print "line "NR" --> "$0}; /TST FINISHED/ {p=0}' a line 5 --> MATCH str3 //line 5 line 6 --> MATCH str4 //line 6 
  • '/TST STARTS/ {p=1} sets the flag p=1 , so now all the lines will be taken into account.
  • p && /MATCH/ {print "line "NR" --> "$0} if the p flag is active and the line contains MATCH , then prints the information.
  • /TST FINISHED/ {p=0} disables the flag when searching for TST FINISHED text.
+2
source share
 sed -n '/TST STARTS/,/TST FINISHED/ { /MATCH/ { =;p } }' log.txt 

line number than the contents of the line in the next line

 | sed "/^[0-9]/ { N s/^\(.*\)\n/line \1:/ }" 

to be included in the same line (can be done in 1 sed, but a huge script and poor performance in this case, the command line recall event is easier with the second sed). You can also put on the previous line numbering.

+2
source share

All Articles