0

If I want to find a line in file and display the surrounding context I use grep -C.

If I also want to limit output to the first few occurrences I add -m parameter

The problem is that grep just stops reading the file after last occurrence, not displaying the context after that line, e.g.

grep -C 1 -m 2 -n "string" filename

would display:

123:line before
124:string - first time
125:line after
--
--
789:line before
790:string - second time

line 791 will not be displayed. This is probably the right behaviour (stop reading immediately after search is done), but how can I display full context anyway?

  • Add Ubuntu and grep version. – Cyrus Jun 24 '15 at 20:30
  • It could be that line 790 is the last line in the file. What does wc -l filename display? – Olathe Jun 24 '15 at 20:40
  • Your output looks strange. There shouldn't be two consecutive -- there. Please show us i) your grep version; ii) a minimal input file that reproduces the problem. What is the string you are looking for? Any special characters? Are you piping the output through something else? – terdon Jun 24 '15 at 22:38
1

Sounds like a bug to me. I'm not experiencing the same problem as you with grep version 2.16.

Assuming it's a bug with your version of grep, perhaps a workaround would be to use -B and -A instead of -C:

grep -A 1 -B 1 -m 2 -n "string" filename

| improve this answer | |

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.