I want to update a string on several text files from command line (bash).
1 Answer
To update string to 'John' only script text files (*.sh) containing the searched string 'Peter' and make backup first (.bak):
¡¡DON'T USE!!
$ sed -i.bak 's/Peter/John/g' $(find bin/ -type f -name '*.sh' \-exec grep -l Peter {} +)
Thanks for your comments Jetchisel and Ed Morton
After research I found this solution (\b is for word limit if you only want to change words):
$ STRING_OLD="\bPeter\b"; STRING_NEW="John"; find bin/ -type f -name '*.sh' -not -name "*.bak" -print0 | xargs -0 grep -Zl "$STRING_OLD" | xargs -t -0 sed -i.bak 's/'"$STRING_OLD"'/'"$STRING_NEW"'/g'
It works with filenames/directories with spaces,tabs,new lines and non ASCII chars.
Variable STRING_OLD is a regexp for sed s/regexp/replacement/ command. You must aware of it.
You also see changed files. It only changes (and backs up) in files where STRING_OLD is found in regexp. The rest of the files remain untouched (that's what I wanted).