27

With the grep command, I found the text I need as follows:

grep 'C02' ~/temp/log.txt Now, whereever I find the desired string, I would like to print the line following the found string.

For example, let's say that the desired text is 'abc', and abc is found on line 12, I would like to print line 13 too.

  • 3
    grep -A1 'abc' ~/temp/log.txt for 1 line of context After the match - see the Context Line Control subsection of the manual (man grep) – steeldriver Nov 3 '16 at 0:44
  • 1
    gnu grep makes it easy; posix does not specify the -A flag – Jeff Schaller Nov 3 '16 at 1:43
  • 1
    hi and welcome to Stack Exchange! on SE, it's expected that you do some basic research before coming here for help. for example, a search for "grep show next line" returned an indirect answer in the first result and a direct answer in the second. what have you done to try to solve this problem already? – strugee Nov 3 '16 at 2:09
36

If you are using Linux system, you can try:

grep -A1 "C02" ~/temp/log.txt


OPTIONS
       -A NUM, --after-context=NUM
              Print NUM lines of trailing context after matching lines.  Places a line containing -- between contiguous groups of matches.
       -B NUM, --before-context=NUM
              Print NUM lines of leading context before matching lines.  Places a line containing -- between contiguous groups of matches.
       -C NUM, --context=NUM
              Print NUM lines of output context.  Places a line containing -- between contiguous groups of matches.

You can use awk also as:

awk '/C02/{print;getline;print}' ~/temp/log.txt
  • 1
    also, sed -n '/C02/{N; p}' ~/temp/log.txt – Sundeep Nov 3 '16 at 1:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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