How can I use -0 option to xargs when specifying the input manually?
For example - as told in the man xargs
-0 Change xargs to expect NUL (``\0'') characters as separators, instead of spaces and newlines. This is expected to be used in concert with the -print0 function in find(1).
find . -print0 | xargs -0 echo
The -0
tells xargs one thing: "Don't separate input with spaces but with NULL char". It is useful usually in combination with find, when you need handle files and/or directories that contain space
in their name.
There are more commands what can play with -print0
- for example grep -z
.
Edit - based on comments:
See Seth's answer or this:
ls -1 | perl -pe 's/\n/\0/;' > null_padded_file.bin
xargs -0 < null_padded_file.bin
But it is strange, why want use -0
if you don't need to use it?. Like "Why want remove a file, if does not exist?". Simply, the -0
is needed to use only with combination, if the input is null-padded. Period. :)
xargs works differently than you think. It takes input and runs the commands provided as arguments with the data it reads from the input. For example:
find dir* -type f -print0 | xargs -0 ls -l
ls -d dir* | xargs '-d\n' ls -l
look foo | xargs echo
look foo | perl -pe 's/\n/\0/;' | xargs -0 echo
You often use -0 if you suspect the input might have spaces or returns embedded in it, so the default argument delimiter of "\s" (regular expression \s, space, tab, newline) isn't good.