仅对包含特定字符串的文件调用sed - 文件名中有空格的问题

时间:2016-08-25 15:38:15

标签: bash sed grep

使用bash,我尝试在文件中进行替换(将B替换为C),但仅限于包含特定字符串A的文件。

我试过

grep -Rl "A" | xargs sed -i 's/B/C'

但是当文件名包含空格

时,这会失败

作为一个丑陋的解决方法,我提出了以下解决方案,用占位符替换空白:

for  FILE in `grep -Rl "A"   | tr " " "@"`; 
  do F1=`echo  $FILE | tr "@" " "`;sed 's/B/C/' "$F1"; 
done

有更优雅的解决方案吗?

3 个答案:

答案 0 :(得分:2)

您可以--null使用grep-0使用xargs

grep --null -Rl 'A' . | xargs -0 sed -i '' 's/B/C/'

--nullgrep命令的每个文件名后输出一个零字节(ASCII NUL字符),xargs -0将空终止输入读取到xargs

答案 1 :(得分:1)

您可以将参数--null for grep的用法与-0的参数结合使用,以使参数由NUL字符分隔。

man grep:
--null  Prints a zero-byte after the file name.

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).

答案 2 :(得分:1)

用于查找文件的UNIX工具的名称恰当,find而不是grep

find . -type f -exec grep -l -Z 'A' {} + |
xargs -0 sed -i 's/B/C'