3

Following the bash-hackers wiki's recommendation, I want to edit files using ed.

In particular I want to do the following with ed instead of sed:

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

I see that ed doesn't have opt like sed's -e, so as far as I know, pipes and io redirections are the only way to work with it non-interactively.

So, using ed from a bash script to do the same as the above sed command would look like:

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

Or

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

But as far as I know it is impossible to involve pipes or io redirections within find's -exec.

Do I miss something? or is the only way to overcome this is to use loops?

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

3 回答 3

4
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 覆盖文件,如果您碰巧有不想破坏的链接,那将是一个问题。

于 2010-05-10T23:55:12.360 回答
1

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

用 find & ed 搜索和替换

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

于 2010-05-11T07:10:16.907 回答
0

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

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

于 2010-05-10T23:39:09.533 回答