Tuesday, January 11, 2011

How to fetch n number of lines before or after a pattern match..

Lets assume there is a file which has 1000 lines. Now i want to see 20 lines from the a pattern (say pattern is 'top secret'). How come..?

Step 1: open the file in command prompt using 'cat' command with -n option(this option shows the content of the file with the line numbers).

Ex: $cat -n ./secrets.txt

step 2: piping the output of the 'step 1' to grep command with -i option(this ignores the case of given pattern i.e case insensitive) and pattern.

Ex: $cat -n ./secrets.txt | grep -i 'top secret'

step 3: now your output gives a line number(say 654) with the give pattern match, so, now using the head & tail commands with the line numbers we get the required output.

Ex: $head -654 | tail -10

Thats all.. :)

No comments: