Linux – print specific line and then some more


I am trying to search a file for a pattern and if the it is found I want to see the line and 10 more lines of the result.

so far I have

grep -n pattern file | cut -d: f1 

now not sure how to use this out put to do the print with the logic like

sed -n result,(result+10)p file

probably going to have a few issued if it pattern is in multiple lines.

Any help is appreciated

Best Answer

if grep -A is not working, try

awk '/pattern/ {for(i=0;i<number_of_lines;i++){print;getline}}' <filename>

else sed has another dirty solution

sed -n '/pattern/ {p;n;p;n;p;...}' <filename> here p-> print, n -> get to next line. So number of p is your number of lines to be printed


to use as a function, write in a

  awk "/$1/"' {for(i=0;i<10;i++){print;getline}}' $2

then just


to run,

jobcheck "pattern" "file"

Update: as per Jonathan Leffler's suggestion, if any of the next 10 lines contains the pattern, counting should start from that line so

pattern  ->start printing from here to next 10 lines
pattern  ->forget about the last 2 lines, start counting from here

So updated awk command will be like

awk '/pattern/{max_line=NR+2} {if(NR<=max_line) print}' <filename>

Similarly inside jobcheck will also be changed. Cheers:)