I have text file:

Line1 aaa
Line2 aaa
Line3 aaa
Line4 importan info about Linux
Line5 infoA
Line6 infoB
Line7

I would like to display line containing word "Linux" and two lines more.

Regarding first part is clear:

cat textfile.txt |grep Linux

But how to display two lines more?

Use the -A option of grep:

cat textfile.txt | grep -A2 Linux

or without the cat:

grep -A2 Linux textfile.txt

Awk alternative approach

$ awk '/Linux/ {print $0; for (i=1;i<=2;i++){ getline; print $0 } }' test-text-file.txt                               
Line4 importan info about Linux
Line5 infoA
Line6 infoB

Or as Pilot6 suggested in the coments, you can do

awk '/Linux/{x=NR+2}(NR<=x)' test-text-file.txt

  • In this case there is no need to use awk. This is an academic answer ;-) And there are lot of much easier ways even with awk. – Pilot6 Sep 18 '15 at 21:32
  • @Pilot6 yes, no need for awk, but since Florian was the "faster gun" this time, I cannot just post same answer. So I'm offering an alternative :) – Sergiy Kolodyazhnyy Sep 18 '15 at 21:34
  • You can omit $0 twice, for instance ;-) – Pilot6 Sep 18 '15 at 21:38
  • awk '/Linux/{x=NR+2}(NR<=x){print}' file – Pilot6 Sep 18 '15 at 21:40
  • OK, that's a little simpler approach – Sergiy Kolodyazhnyy Sep 18 '15 at 21:49

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.