简体   繁体   English

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

[英]Invoke sed only on files which contain a certain string - problems with whitespaces in filenames

Using bash, I try to make a substitutions in files (replace B with C ), but only in files which contain a certain string A . 使用bash,我尝试在文件中进行替换(用C替换B ),但仅限于包含特定字符串A

I tried 我试过了

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

But this fails when the filenames contain whitespaces 但是当文件名包含空格时,这会失败

As an ugly workaround, I came up with the following solution which replaces the whitespaces with a placeholder : 作为一个丑陋的解决方法,我提出了以下解决方案,用占位符替换空白:

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

is there a more elegant solution? 有更优雅的解决方案吗?

You can use --null for grep and -0 for xargs : 您可以将--null用于grep ,将-0用于xargs

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

--null Outputs a zero byte (the ASCII NUL character) after each filename of grep command and xargs -0 reads null terminated input to xargs . --nullgrep命令的每个文件名后输出一个零字节(ASCII NUL字符), xargs -0读取到xargs空终止输入。

You could combine the usage of argument --null for grep, with the argument of -0 for xargs, to have the arguments be separated by NUL characters instead. 您可以将参数-null for grep的用法与xargs的-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).

The UNIX tool to find files is named, appropriately enough, find not grep . 用于查找文件的UNIX工具被命名,恰当地说, find grep

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM