Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print 5 consecutive lines after a pattern in file using awk [duplicate]

Tags:

shell

unix

awk

I would like to search for a pattern in a file and prints 5 lines after finding that pattern.

I need to use awk in order to do this.

Example:

File Contents:

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

How do I parse through a file and print only the above mentioned lines? Do I use the NR of the line which contains "PATTERN" and keep incrementing upto 5 and print each line in the process. Kindly do let me know if there is any other efficient wat to do it in Awk.

like image 931
tomkaith13 Avatar asked Mar 15 '11 18:03

tomkaith13


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

How do I print next line in awk?

Original answer: Append printf "\n" at the end of each awk action {} . printf "\n" will print a newline.

What is awk '{ print $3 }'?

txt. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

How do I print awk lines?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.


2 Answers

Another way to do it in AWK:

awk '/PATTERN/ {for(i=1; i<=5; i++) {getline; print}}' inputfile 

in sed:

sed -n '/PATTERN/{n;p;n;p;n;p;n;p;n;p}' inputfile 

in GNU sed:

sed -n '/PATTERN/,+7p' inputfile 

or

sed -n '1{x;s/.*/####/;x};/PATTERN/{:a;n;p;x;s/.//;ta;q}' inputfile 

The # characters represent a counter. Use one fewer than the number of lines you want to output.

like image 156
Dennis Williamson Avatar answered Sep 20 '22 14:09

Dennis Williamson


awk ' {      if (lines > 0) {         print;         --lines;     } }  /PATTERN/ {     lines = 5 }  ' < input 

This yields:

#Line1 #Line2 #Line3 #Line4 #Line5 
like image 24
Johnsyweb Avatar answered Sep 18 '22 14:09

Johnsyweb