使用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
有更优雅的解决方案吗?
答案 0 :(得分:2)
您可以--null
使用grep
,-0
使用xargs
:
grep --null -Rl 'A' . | xargs -0 sed -i '' 's/B/C/'
--null
在grep
命令的每个文件名后输出一个零字节(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'