0

Why is grep returning non-matched lines? You can see grep highlights the match. How can I get the desired behavior? This is in Ubuntu.

$ service --status-all | grep 'friendly'
[ ? ] apport
[ ? ] console-setup
[ ? ] cryptdisks
[ ? ] cryptdisks-early
[ ? ] dns-clean
[ + ] friendly-recovery
[ ? ] irqbalance
[ ? ] killprocs

Nothing funny in the alias.

$ alias
alias grep='grep --color=auto'
James
  • 2,148
  • 2
  • 25
  • 39
  • 2
    Cannot seem to replicate. – Jonnix Oct 15 '16 at 16:13
  • 1
    at command line type: "which grep" to see which grep you are using. I just tried your command (using the same alias) and only get output containing the expected match. I am running Ubuntu. – StvnBrkdll Oct 15 '16 at 16:16

2 Answers2

3

Looks like it's not grep. It is stderr being sent to the console.

$ service --status-all > test.txt
 [ ? ]  apport
 [ ? ]  console-setup
 ...

vs.

$ service --status-all 2> test.txt
<no output>

So a possible solution is to redirect stderr to stdout then grep:

$ service --status-all 2>&1 | grep 'friendly'
[ + ] friendly-recovery

James
  • 2,148
  • 2
  • 25
  • 39
0

You can control the amount of context displayed before and after the match using the -C flag, i.e service --status-all | grep -C 0 'friendly' will only display the exact lines that matched without any context.

For more information you can see this answer: https://stackoverflow.com/a/9083/2791719

Community
  • 1
  • 1
Fan Pu
  • 86
  • 8