Jacob Krieg
Jacob Krieg

Reputation: 3164

Extract Nth line after matching pattern

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?

Upvotes: 7

Views: 22724

Answers (3)

Ed Morton
Ed Morton

Reputation: 203189

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.

Upvotes: 32

Veda
Veda

Reputation: 2063

I like solutions I can learn to redo, without having to google for it every time. This solution is not perfect, but uses simple grep commands that I can write from memory.

grep -A7 "searchpattern" file | grep -B1 "^--$" | grep -v "^--$"

You can change the 7 to the nth line you want after the search pattern. It then searches for the "group separator" -- and shows the last line before that. Then remove the group separators.

The only case this does not work correctly is if your data contains lines with only "--".

Upvotes: 2

lerems04
lerems04

Reputation: 61

Printing the lnbth 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 lnbth 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 lnbth lines after regular-expression match:

  • Using perl(bash example):

    perl -ne '/regex/ && $k++;$k!=0 && $k++ && $k=='"$lnb"'+2 && (print,$k=0)' my_file
    

Upvotes: 6

Related Questions