繁体   English   中英

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

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

使用bash,我尝试在文件中进行替换(用C替换B ),但仅限于包含特定字符串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

有更优雅的解决方案吗?

您可以将--null用于grep ,将-0用于xargs

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

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

您可以将参数-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).

用于查找文件的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