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
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.
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.
Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.
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 ...
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With