I am using the following command on a Unix server:
find . -type f -name "*.txt" | xargs grep -li 'needle'
Since grep -R
is not available, I have to use this find/xargs solution. Every time a file cannot be opened, grep
tells me this:
grep: can't open "foo.txt"
I want to get rid of this message, so I tried to redirect stderr to /dev/null
, but somehow this is not working.
find . -type f -name "*.txt" | xargs grep -li 'needle' 2>/dev/null
I want to preserve stdout (i.e. write the results to the console), and only hide these grep error messages. Instead of 2>
, I also tried &>
, but this also did not work. How can I fix this?
In Unix, how do I redirect error messages to /dev/null? You can send output to /dev/null, by using command >/dev/null syntax. However, this will not work when command will use the standard error (FD # 2). So you need to modify >/dev/null as follows to redirect both output and errors to /dev/null.
The operator '>' , called a redirection operator, writes data to a file. The file specified in this case is /dev/null. Hence, the data is ultimately discarded. If any other file were given instead of /dev/null, the standard output would have been written to that file.
Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.
/dev/null is a special filesystem object that discards everything written into it. Redirecting a stream into it means hiding your program's output. The 2>&1 part means "redirect the error stream into the output stream", so when you redirect the output stream, error stream gets redirected as well.
In order to redirect stderr to /dev/null use:
some_cmd 2>/dev/null
You don't need xargs
here. (And you don't want it! since it performs word splitting)
Use find's exec option:
find . -type f -name "*.txt" -exec grep -li needle {} +
To suppress the error messages use the -s
option of grep
:
From man grep
:
-s, --no-messages Suppress error messages about nonexistent or unreadable files.
which gives you:
find . -type f -name "*.txt" -exec grep -lis needle {} +
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With