For portability, I don't rely on features of sed that are specific to linux or BSD. Instead I use the overwrite
script from Kernighan and Pike's book on the Unix Programming Environment.
The command is then
find /the/folder -type f -exec overwrite '{}' sed 's/old/new/g' {} ';'
And the overwrite
script (which I use all over the place) is
#!/bin/sh
# overwrite: copy standard input to output after EOF
# (final version)
# set -x
case $# in
0|1) echo 'Usage: overwrite file cmd [args]' 1>&2; exit 2
esac
file=$1; shift
new=/tmp/$$.new; old=/tmp/$$.old
trap 'rm -f $new; exit 1' 1 2 15 # clean up files
if "$@" >$new # collect input
then
cp $file $old # save original file
trap 'trap "" 1 2 15; cp $old $file # ignore signals
rm -f $new $old; exit 1' 1 2 15 # during restore
cp $new $file
else
echo "overwrite: $1 failed, $file unchanged" 1>&2
exit 1
fi
rm -f $new $old
The idea is that it overwrites a file only if a command succeeds. Useful in find
and also where you would not want to use
sed 's/old/new/g' file > file # THIS CODE DOES NOT WORK
because the shell truncates the file before sed
can read it.