techie11
techie11

Reputation: 1387

How to print 2 consecutive lines after a pattern in file using awk and the matched line itself

In a text file as following,

####PATTERN#######
#Line1
#Line2
#Line3
#Line4
####PATTERN#######
#Line1
#Line2
#Line3
#Line4
#Line5
####PATTERN#######
#Line1
#Line2
#Line3
#Line4

I would like to extract the matched line and the next 2 lines. the output should be:

####PATTERN#######
#Line1
#Line2
####PATTERN#######
#Line1
#Line2
####PATTERN#######
#Line1
#Line2

How to achieve this?

Thanks, Alex

Upvotes: 1

Views: 6318

Answers (3)

hwnd
hwnd

Reputation: 70732

There is a straightforward way to do this using grep. You will get -- lines between your context, and can use an inverted match -v to remove them. See the documentation from the grep man page.

grep -A2 "PATTERN" file | grep -v -- "^--$"

Using awk:

awk '/PATTERN/{c=NR+2}(NR<=c){print}' file

Using sed:

sed '/PATTERN/,+2!d' file

Perl one-liner

perl -ne 'print if (/PATTERN/ and $p=2) .. not $p--' file

Upvotes: 2

Kevin
Kevin

Reputation: 56069

With awk, as requested

awk '/PATTERN/{c=3}c&&c--' file

or

awk '/PATTERN/{c=3}c-->0' file

But it's easier with grep:

grep -A2 file

Upvotes: 3

anubhava
anubhava

Reputation: 785156

Use this awk:

awk '/PATTERN/{s=1} s++ < 4' file

####PATTERN#######
#Line1
#Line2
####PATTERN#######
#Line1
#Line2
####PATTERN#######
#Line1
#Line2

Upvotes: 2

Related Questions