54

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

grep 'C02' ~/temp/log.txt

Now, wherever 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.

4
  • 5
    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) Commented Nov 3, 2016 at 0:44
  • 2
    gnu grep makes it easy; posix does not specify the -A flag Commented Nov 3, 2016 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? Commented Nov 3, 2016 at 2:09
  • You should use grep -F 'C02' instead as it is faster. grep -F matches fixed strings. such as 'C02' Commented Nov 2, 2021 at 16:52

1 Answer 1

63

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
2
  • 3
    also, sed -n '/C02/{N; p}' ~/temp/log.txt Commented Nov 3, 2016 at 1:53
  • 1
    For anyone wondering, for example -A9 will add 9 rows so that there are 10 shown in the output, not just the 0th and the ninth row. Commented Sep 8, 2022 at 18:10

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.