Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed and grep get the line number for a match

Tags:

grep

bash

sed

I have a log file and i use sed to extract the lines between two strings which contains the word MATCH. I use sed to extract the lines and grep to only take the lines containing the word "MATCH". I would need the lines number in the log file where a match is 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 lines:

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

My output is:

MATCH str3
MATCH str4

But I also need in the output the lines number:

line 5: MATCH str3
line 6: MATCH str4
like image 459
georgiana_e Avatar asked Nov 15 '13 10:11

georgiana_e


People also ask

How do I grep and show line numbers?

To Display Line Numbers with grep MatchesAppend the -n operator to any grep command to show the line numbers. We will search for Phoenix in the current directory, show two lines before and after the matches along with their line numbers.

How do I print line numbers using sed?

SED : Using 'p' command for printing particular line number We are using same content of file (/tmp/test) for explanation as we have used in above section. We will print the line number 3 from /tmp/test file. Syntax: -n = Nothing will print unless an explicit request to print is found.

How do you grep a line after a match?

Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.


2 Answers

You could use:

cat -n

to number the lines before you apply your sed, like this:

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

Alternatively, you could replace cat -n with a variant of nl:

nl -n ln log.txt | sed ...
like image 180
Mark Setchell Avatar answered Sep 28 '22 07:09

Mark Setchell


My first attempt wasn't keeping the line number, because the sed part removes 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 a flag p=1 so that from now on all lines will be taken into account.
  • p && /MATCH/ {print "line "NR" --> "$0} if the flag p is active and the line contains MATCH, then it prints the info.
  • /TST FINISHED/ {p=0} turns the flag off when finding TST FINISHED text.
like image 25
fedorqui 'SO stop harming' Avatar answered Sep 28 '22 05:09

fedorqui 'SO stop harming'