I want to extract the Nth line after a matching pattern using grep
, awk
or sed
.
For example I have this piece of text:
Revision:
60000<br />
And I want to extract 60000.
I tried Revision:([a-z0-9]*)\s*([0-9]){5}
which matches the Revision together with the revision number but when I pass it to grep: grep Revision:([a-z0-9]*)\s*([0-9]){5} file.html
I get nothing.
How can I achieve this?
You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines. Save this answer.
Use grep to select lines from text files that match simple patterns. Use find to find files and directories whose names match simple patterns. Use the output of one command as the command-line argument(s) to another command.
For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after. Save this answer.
The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.
To extract the Nth line after a matching pattern
you want:
awk 'c&&!--c;/pattern/{c=N}' file
e.g.
awk 'c&&!--c;/Revision:/{c=5}' file
would print the 5th line after the text "Revision:"/.
See Printing with sed or awk a line following a matching pattern for more information.
Printing the lnb
th line after first blank/empty line:
Index of line to print (in bash shell):
lnb=2
Using sed
:
sed -ne '/^\s*$/{:a;n;0~'"$lnb"'!ba;p;q}' my_file`
Using perl
:
perl -ne '/^\s+$/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,last)' my_file`
Printing the lnb
th line after regular-expression match:
Using sed
:
sed -ne '/regex/{:a;n;0~'"$lnb"'!ba;p;q}' my_file
Using perl
:
perl -ne '/regex/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,last)' my_file
Bonus 1, Windows PowerShell (install Perl first) :
$lnb=2
perl -ne "/regex/ && `$k++;`$k!=0 && `$k++ && `$k==$lnb+2 && (print,last)" my_file
Bonus 2, Windows DOS command line :
set lnb=2
perl -ne "/regex/ && $k++;$k!=0 && $k++ && $k==%lnb%+2 && (print,last)" my_file
Printing ALL lnb
th lines after regular-expression match:
Using perl
(bash example):
perl -ne '/regex/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,$k=0)' my_file
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