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
?
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:
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
.
grep
has the option -s
or --no-messages
to suppress error messages about nonexistent or unreadable files.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.