Dla przenośności, nie polegam na funkcjach sed, które są specyficzne dla Linuksa lub BSD. Zamiast tego używam skryptu overwrite
z książki Kernighana i Pike'a z Unix Programming Environment.
Polecenie jest wtedy
find /the/folder -type f -exec overwrite '{}' sed 's/old/new/g' {} ';'
A overwrite
skrypt (którego używam wszędzie) jest
#!/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 "[email protected]" >$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
Chodzi o to, że nadpisuje plik tylko wtedy, gdy polecenie powiedzie. Przydatne w find
a także wtedy, gdy nie chcesz używać
sed 's/old/new/g' file > file # THIS CODE DOES NOT WORK
ponieważ powłoka obcina plik przed sed
można go odczytać.
http://theunixshell.blogspot.com/2012/12/find-and-replace-string-in-all-files.html – Vijay