Using ed to manipulate files matched by find
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 somet开发者_如何学Pythonhing? 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;
find . -type f -exec bash -c 'ed -s "$2" <<< "$1"' _ $'g/a/s//b/g\nw' {} \;
And a POSIX version:
find . -type f -exec sh -c 'printf "%s\n" "g/a/s//b/g" w | ed -s "$1"' _ {} \;
The main reason to use ed over sed -i is that ed edits files while sed -i overwrites files, and that's a problem if you happen to have links you don't want to break.
This find & ed snippet features a test mode (so you can verify you got your regex right before an acutal mass replace operation):
Search & replace with find & ed
http://codesnippets.joyent.com/posts/show/2299
Put the ed command with all the redirections and "here documents" in a shell script, and invoke that from find.
But I have to ask: why ed? What do you think you can do with ed that you can't do with sed?
精彩评论