Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 仅在包含特定字符串的文件上调用sed-文件名中存在空格问题_Bash_Sed_Grep - Fatal编程技术网

Bash 仅在包含特定字符串的文件上调用sed-文件名中存在空格问题

Bash 仅在包含特定字符串的文件上调用sed-文件名中存在空格问题,bash,sed,grep,Bash,Sed,Grep,使用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 有更优雅

使用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
有更优雅的解决方案吗?

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

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

--null
grep
命令的每个文件名之后输出一个零字节(ASCII NUL字符),并且
xargs-0
读取以null结尾的输入到
xargs

您可以将参数--null用于grep,参数-0用于xargs,改为使用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'

也请看,谢谢!当然我知道find,但是您的解决方案仍然使用grep(因此您使用3个工具而不是2个)。我也尝试了你的解决方案,但我无法让它工作,因为我缺少-Z表示grep,缺少-0表示xargs来处理空白。因此,使用find而不是grep并不能回答我的问题……我并没有说不要使用grep,我说的是使用
find
find
文件,然后
grep
g/re/p
。是的,3个工具比2个好。在这种情况下,GNU的家伙们违背了UNIX的理念,即每个工具都能很好地完成一件事,因为他们给了grep查找文件的能力(下一个选项是对输出进行排序,还是粘贴不同文件的输出?)现在GNU grep只是一堆混乱的无关论点。当您使用GNU grep选项
-R
时,您怎么会丢失nul终止文件名的GNU grep和xargs选项?