'grep after grep : No such file or directory
To create a test file contains blanks in the filename first:
vim "/tmp/it is a test.txt"
bash escape
Search with grep:
grep -lr 'bash' /tmp
/tmp/it is a test.txt
I want to grep command after the grep:
grep -lr 'bash' /tmp | xargs grep escape
grep: /tmp/it: No such file or directory
grep: is: No such file or directory
grep: a: No such file or directory
grep: test.txt: No such file or directory
So i add -0
in xargs:
grep -lr 'bash' /tmp | xargs -0 grep escape
grep: /tmp/it is a test.txt
: No such file or directory
I find the reason:
grep -lr 'bash' /tmp | xargs -0
grep: /tmp/it is a test.txt
#a blank line at the bottom
xargs -0
add a blank line!
How can suppress the output : No such file or directory
?
Solution 1:[1]
As you may have guessed, the first version you tried
grep -lr 'bash' /tmp | xargs grep escape
failed because xargs
assumes arguments taken from standard input are delimited by:
space, tab, newline and end-of-file.
You were on the good track by adding the -0
CLI option:
grep -lr 'bash' /tmp | xargs -0 grep escape
But to make it fully working, you'll also need to ensure that xargs
's input is indeed delimited by NUL
characters.
Hence the following command that relies on tr
:
grep -lr 'bash' /tmp | tr '\n' '\0' | xargs -0 grep escape
Alternatively, a better solution amounts to directly using grep
's --null
CLI option:
grep -lr --null 'bash' /tmp | xargs -0 grep escape
or more concisely:
grep -lrZ 'bash' /tmp | xargs -0 grep escape
As an aside
I find the reason:
xargs -0
add a blank line!
To explain this further:
xargs -0
alone amounts to xargs -0 echo
, and because of -0
, xargs
sees the final newline printed by grep
(included as you didn't use the --null
CLI option) as a character that is part of the filename… which is then printed by echo
.
Solution 2:[2]
grep
has the option -s
or --no-messages
to suppress error messages about nonexistent or unreadable files.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | schorsch312 |