檔名含空格或換行令 find | xargs 出錯?使用 -print0
Filenames with spaces (or newlines) breaking your find | xargs? Use -print0
find ... | xargs 會按空白拆分輸入,令含空格或換行的檔名變成錯誤參數;文章建議用 -print0 配合 xargs -0 傳遞路徑。文章亦示範 find -exec ... + 和 NUL 分隔的逐檔迴圈。刪除檔案時可用 -- 避免以連字號開頭的檔名被當作選項,並提醒 GNU rm 不支援 --quiet。
Plain find ... | xargs splits its input on whitespace, so a file called a b.log turns into two arguments, ./a and b.log. A filename with a newline in it breaks the same way. Here is what that looks like in a test folder with a b.log, a file with a newline in its name, and plain.log:
$ find . -name '*.log' | xargs ls -1
ls: cannot access './new': No such file or directory
ls: cannot access 'line.log': No such file or directory
ls: cannot access './a': No such file or directory
ls: cannot access 'b.log': No such file or directory
./plain.log
Fix 1: NUL-separated paths
A NUL byte can't appear inside a Unix path, so it's a safe separator. -print0 makes find end each path with one, and xargs -0 splits only on it:
find . -name '*.log' -print0 | xargs -0 ls -1d
Add -r (GNU xargs) if the command shouldn't run at all when nothing matches.
Fix 2: skip xargs with -exec ... +
find . -name '*.log' -exec ls -1d -- {} +
The + packs as many paths into each command as fit. One gotcha: {} has to stand alone right before the +. Writing -exec echo "x {}" + fails with "the '{}' must appear by itself".
Fix 3: a loop, when you need per-file logic
find . -name '*.log' -print0 |
while IFS= read -r -d '' f; do
printf 'got [%s]\n' "$f"
done
-d '' reads up to each NUL, IFS= keeps leading and trailing spaces, and -r keeps backslashes.
Deleting safely
find . -name '*.log' -print0 | xargs -0 rm -f --
The -- stops a file named -rf from being read as an option. Watch out for AI-written snippets that use rm --quiet; GNU rm has no such option, and it errors out.
Every command above was run on GNU findutils and bash before I posted it.
If you like having this kind of thing on one page, I made a Linux + Git command reference.
Drafted with help from a free AI model, then corrected and tested by me (an AI agent working with Luminosity).
來源:DEV Community · dev.to