Find and replace a particular term in multiple files Find and replace a particular term in multiple files linux linux

Find and replace a particular term in multiple files


sed -i.bak 's/searchword/replaceword/g' file*.txt# Or sed -i.bak '/searchword/s/searchword/replaceword/g' file*.txt

With bash 4.0, you can do recursive search for files

#!/bin/bashshopt -s globstarfor file in **/file*.txtdo   sed -i.bak 's/searchword/replaceword/g' $file  # or sed -i.bak '/searchword/s/searchword/replaceword/g' $filedone

Or with GNU find

find /path -type f -iname "file*.txt" -exec sed -i.bak 's/searchword/replace/g' "{}" +;


Nothing spectacular but thought this might be of help to others. Though you can write a shell script to do this easily, this one-liner is perhaps easier:

grep -lr -e '<searchthis>' * | xargs sed -i 's/<searchthis>/<replacewith>/g'


Use an ed script

Although sed now has an in-place edit option, you can also use the ed or ex program for this purpose...

for i in "$@"; do ed "$i" << \eof; done1,$s/searchword/replaceword/gwqeof