Computing.Net > Forums > Unix > Extract multiple lines from file

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Extract multiple lines from file

Reply to Message Icon

Name: irateb
Date: September 15, 2009 at 10:41:24 Pacific
OS: AIX
CPU/Ram: n/a
Subcategory: General
Comment:

Hello,

I have a file that I need to extract multiple lines out of. When I find a certain keyword in the file, I need that line and the next 2 lines (three lines in total). This happens several times a file. I found this script on the internet:

sed -n '
/keyword/ {
N
/\n.*/ p
}' input > output

Which works, but only gives me the line with the keyword and the next line. How do I get the third line?

Thanks!



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: September 15, 2009 at 22:24:06 Pacific
Reply:

Just add another N:

sed -n '
/keyword/ {
N
N
/\n.*/ p
}' input > output


1

Response Number 2
Name: irateb
Date: September 16, 2009 at 04:48:24 Pacific
Reply:

I couldn't decide if I should put '2N' or if it was just another 'N', and then if the Ns could go together or the second N needed to be on a new line or if it even mattered, and I got pulled away before I could try anything. Thank you very much nails!


0

Response Number 3
Name: ghostdog
Date: September 17, 2009 at 06:22:38 Pacific
Reply:

why don't you just use grep with -A option..
eg

 grep -A 2 "pattern" file

GNU win32 packages | Gawk


0

Response Number 4
Name: nails
Date: September 17, 2009 at 06:31:14 Pacific
Reply:

The grep -A option is relatively new. It's not available on the older *nix versions. Yes, it is possible to download the new version for your unix flavor at gnu.org.


0

Response Number 5
Name: ghostdog
Date: September 17, 2009 at 06:48:55 Pacific
Reply:

yes. its GNU option. i see OP has AIX (presumably). here's another one with awk

awk 'c&&c--;/pattern/{c=2}' file
. No Aix machine to test, but should work. If not do it the old fashion way
 awk '/pattern/{getline;print;getline;print}' file

GNU win32 packages | Gawk


0

Related Posts

See More



Sponsored Link
Ads by Google
Reply to Message Icon





Use following form to reply to current message:

Login or Register to Reply
LoginRegister


Sponsored links

Ads by Google


Results for: Extract multiple lines from file

Extracting multipe lines from file www.computing.net/answers/unix/extracting-multipe-lines-from-file/8227.html

Process line from file -Cshell scr www.computing.net/answers/unix/process-line-from-file-cshell-scr/5072.html

extract a specific line from file www.computing.net/answers/unix/extract-a-specific-line-from-file/5381.html