I want to print next 3 lines after pattern matching.

Dear Experts,
I have file called file1 in which i am greping a pattern after that i want to next 3 lines when that pattern is matched.

Ex:- file1

USA
UK
India
Africa
Hello
Asia
Europe
Australia
Hello
Peter
Robert
Jo
i want to next 3 lines after matching Hello pattern. i.e output should be.
Asia
Europe
Australia
Peter
Robert
Jo

Thanks & Regards
Naree

hi....
Do you want the next three lines or all the lines after the pattern matching.
Your required output shows that you want all the lines after the pattern matching.
Be clear on your requirement first.

using Sed:

sed -n '/Hello/ {n; p; n; p; n; p}' filename

grep -A 3 "Hello" file.txt

Hi Yogesh,
When i use sed -n '/Hello/ (n; p; n; p; n; p)' file1 It is throwing unrecognized command. '/Hello/.. Can u help me in another way..

Here is the same in perl:

#!/usr/bin/perl

open (FH,"blah.txt") || "die can't open file $!";

while (<FH>) {
        last if /Hello/ }

my ($curr, $next1, $next2, $next3)=<FH>;
close FH;

print "$curr$next$next2$next3";

Dear Experts,
grep -A is not working in Solaris O.S. Please can anyone help in awk .

Thanks & Regards
Naree

You seem to have mistyped Yogesh's sed command. Try to copy+paste it so you get it exactly.

If you want to use AWK code :

awk '/Hello/{getline;print}' filename.

But I wonder whether getline would work in SUN-Solaris....
Can you tell the forum which version u are using....I will try to search out....

Or like this.

awk '/Hello/ { p=3; next } p { p--; print }' filename

Or this:

nawk '_&&_--;/Hello/{_=3}' file

Here is the command using sed for above output

sed -n '/Hello/{n;N;N;p;}' filename

Yes,
the only problem is when you want to print the 42th line for instance :slight_smile: