【问题标题】:Invoke sed only on files which contain a certain string - problems with whitespaces in filenames仅在包含特定字符串的文件上调用 sed - 文件名中的空格问题
【发布时间】:2017-01-02 03:08:11
【问题描述】:

使用 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

有没有更优雅的解决方案?

【问题讨论】:

标签: bash sed grep


【解决方案1】:

您可以将--null 用于grep 和-0 用于xargs:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      用于查找文件的 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 能够查找文件时,每个工具都做得很好(sorting 输出的下一个选项是什么,或者怎么样pasteing 来自不同文件的输出?)现在 GNU grep 只是一堆令人困惑的不相关参数。当您使用 GNU grep 选项 -R 时,您怎么会缺少用于 nul 终止文件名的 GNU grep 和 xargs 选项?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多