grep -l 输出带空格的文件名

doc*_*_id 5 bash grep path sed

我想循环文件

for f in `grep -rsl "foo" . `: do sed -i -- "s/foo/bar/g" $f; done;

但由于文件名包含空格,因此只要找到空格,就会拆分文件名。

如何将文件名及其空格传递给do块?

Joh*_*024 5

对于处理困难的文件名,最好用 NUL 字符分隔文件名。GNUgrep通过--null选项xargs支持这一点,并通过-0选项支持这一点。因此,尝试:

grep --null -rslZ "foo" | xargs -0 sed -i -- "s/foo/bar/g"
Run Code Online (Sandbox Code Playgroud)

使用 shell 循环

grep --null -rslZ "foo" | while IFS= read -r -d $'\0' file
    do 
        sed -i -- "s/foo/bar/g" "$file"
    done
Run Code Online (Sandbox Code Playgroud)