awk print Nth line after matching a pattern

 

By using awk we can print only Nth line after matching a pattern.

Lets say I have a file test.txt with following content and I want to extract 5 line after matching pattern.

$ cat test.txt

1
2
3
4
5
6
7
8
9

Use following awk code to extract Nth line:

Syntax:

$ awk 'c&&!--c;/pattern/{c=N}' file

where “pattern” is your input pattern and N is a line number to extract after matching pattern.

$ awk 'c&&!--c;/1/{c=5}' test.txt

Output:

6

In above example I am trying to extract 5th line after matching pattern, here my input pattern is 1 and 5th line after matching pattern is 6. So our output is 6.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s