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.
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.
Original answer: Append printf "\n" at the end of each awk action {} . printf "\n" will print a newline.
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.
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.
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.
awk ' { if (lines > 0) { print; --lines; } } /PATTERN/ { lines = 5 } ' < input
This yields:
#Line1 #Line2 #Line3 #Line4 #Line5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With