Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print specific number of lines after matching pattern

I have to print 81 lines after each occurrence of the expression "AAA" from my input file. How do I go about that?

like image 325
user2517597 Avatar asked Jun 24 '13 19:06

user2517597


People also ask

How do you grep a specific line after a match?

Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.

Which command is used to extract lines with matching pattern from a file?

Use grep to select lines from text files that match simple patterns. Use find to find files and directories whose names match simple patterns. Use the output of one command as the command-line argument(s) to another command.

How do I print a specific line in awk?

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.


1 Answers

The following idioms describe how to select a range of records given a specific pattern to match:

a) Print all records from some pattern:

awk '/pattern/{f=1}f' file

b) Print all records after some pattern:

awk 'f;/pattern/{f=1}' file

c) Print the Nth record after some pattern:

awk 'c&&!--c;/pattern/{c=N}' file

d) Print every record except the Nth record after some pattern:

awk 'c&&!--c{next}/pattern/{c=N}1' file

e) Print the N records after some pattern:

awk 'c&&c--;/pattern/{c=N}' file

f) Print every record except the N records after some pattern:

awk 'c&&c--{next}/pattern/{c=N}1' file

g) Print the N records from some pattern:

awk '/pattern/{c=N}c&&c--' file

I changed the variable name from "f" for "found" to "c" for "count" where appropriate as that's more expressive of what the variable actually IS.

So, you'd want "e" above:

awk 'c&&c--;/AAA/{c=81}' file
like image 90
Ed Morton Avatar answered Oct 19 '22 05:10

Ed Morton