Amazon.com Widgets

Safer in-place edit?

Sometimes I need to edit a file in batch mode. Say you have /etc/default/foo and you want to change BAR="-c5" to BAR="-c4". One of the popular methods is using sed in-place edit, like this:

sed -i -e 's/BAR="-c5"/BAR="-c4"/' foo

If your version of sed is antiquated and doesn’t support in-place editing you can do the same using perl:

perl -i -p -e 's/BAR="-c5"/BAR="-c4"/' foo

The problem with this approach is that if the needle doesn’t exist, sed and perl will silently skip doing the replacement. For example if upstream changes BAR="-c5" to BAR="-c3" then your sed/perl will happily and silently leave it at -c3 instead of changing to -c4 and most probably you will not notice until much later.

One can use patch instead, but it is somewhat clumsy to save a diff file with at least 5 lines in it, just to change one character in the input file…

There’s always the possibility to add some more perl code and make it:

perl -i -pe 's/BAR="-c5"/BAR="-c4"/ and $e|=1; END{exit(!$e)}' foo

I feel this is hackish and somewhat error prone though.

What’s your solution?

Leave a Reply

WP-SpamFree by Pole Position Marketing

Currently you have JavaScript disabled. In order to post comments, please make sure JavaScript and Cookies are enabled, and reload the page. Click here for instructions on how to enable JavaScript in your browser.