I have a command example,

device list

which gives me all devices with their status as okay or error in the following format

[okay     ]:  you are listening on : 11
[error    ]:  not currently listening: 22
[error    ]:  not currently listening: 33
[okay     ]:  you are listening on : 111

I want to print only devices that has status as okay.

I tried using grep command as

device list | grep -r 'okay'
device list | grep -r '[okay     ]'
device list | grep -r '^okay'
device list | grep  'okay'

But it didn't print any output. How can I print the devices with status as okay.

Thanks in advance.


You don't have to use -r option with grep in this case, because (look at man grep):

-r, --recursive
              Read all files  under  each  directory,  recursively,  following
              symbolic  links  only  if they are on the command line.  This is
              equivalent to the -d recurse option.

You also have to redirect and errors from the standard output to be piped by the grep command using 2>&1 redirection:

device list 2>&1 | grep 'okay'

Or you can use |&:

device list |& grep 'okay'
| improve this answer | |

From the output given to us, at least the version of the grep should have been able to work. If it doesn't, the only possible reason is because this command doesn't print its output on STDOUT but on STDERR. Both are displayed on any terminal/console by default, but commands like grep when takin its input via a pipe (|) do this from STDOUT only.

The solution is to redirect the output of STDERR to STDOUT, this is what the 2>&1 or |& will do :

$ device list 2>&1 | grep okay
$ device list |& grep okay

The 3 first forms of your command, using grep -r will never works, even if you redirect the output of STDERR because the -r option is used to recurse into directory and subdirectory. So even if used after a pipe, grep -r something will search something in files in all directories from where you run the command.

| improve this answer | |

Remove the -r option of your grep command and it will work:

device list | grep 'okay'

-r is for recursive search.

| 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.