【问题标题】:Using ed to manipulate files matched by find使用 ed 操作 find 匹配的文件
【发布时间】:2010-05-10 23:32:57
【问题描述】:

按照bash-hackers wiki's recommendation,我想用ed编辑文件。

我特别想用 ed 而不是 sed 来做以下事情:

find . -type f -exec sed -i -e 's/a/b/g' {} \;

我看到 ed 没有像 sed 的 -e 那样的 opt,据我所知,管道和 io 重定向是非交互地使用它的唯一方法。

因此,使用 bash 脚本中的 ed 来执行与上述 sed 命令相同的操作如下所示:

ed file_name <<<$'g/a/s//b/g\nw'

或者

echo $'g/a/s//b/g\nw' | ed file_name

但据我所知,在 find 的 -exec 中不可能涉及管道或 io 重定向。

我错过了什么吗?或者克服这个问题的唯一方法是使用循环?

for file in $(find . -type f -print); do ed $file <<<$'g/a/s//b/g\nw'; done;

【问题讨论】:

    标签: bash find gnu-coreutils ed


    【解决方案1】:
    find . -type f -exec bash -c 'ed -s "$2" <<< "$1"' _ $'g/a/s//b/g\nw' {} \;
    

    还有一个 POSIX 版本:

    find . -type f -exec sh -c 'printf "%s\n" "g/a/s//b/g" w | ed -s "$1"' _ {} \;
    

    使用 ed 而不是 sed -i 的主要原因是 ed 编辑文件,而 sed -i 覆盖文件,如果您碰巧有不想破坏的链接,那就是个问题。

    【讨论】:

      【解决方案2】:

      此 find & ed sn-p 具有测试模式(因此您可以在执行大规模替换操作之前验证您的正则表达式):

      用 find & ed 搜索和替换

      http://codesnippets.joyent.com/posts/show/2299

      【讨论】:

        【解决方案3】:

        将带有所有重定向和“此处文档”的 ed 命令放在一个 shell 脚本中,然后从 find 中调用它。

        但我不得不问:为什么是 ed?你认为你可以用 ed 做什么而你不能用 sed 做什么?

        【讨论】:

        • 查看我提到的链接,以及 geirha 的回答。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-21
        相关资源
        最近更新 更多