Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace a particular term in multiple files

How can I replace a particular term in multiple files in Linux?

For instance, I have a number of files in my directory:

file1.txt file2.txt file3.txt

And I need to find a word "searchword" and replace it with "replaceword".

like image 673
Legend Avatar asked Feb 15 '10 03:02

Legend


2 Answers

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/bash
shopt -s globstar
for file in **/file*.txt
do 
  sed -i.bak 's/searchword/replaceword/g' $file
  # or sed -i.bak '/searchword/s/searchword/replaceword/g' $file
done

Or with GNU find

find /path -type f -iname "file*.txt" -exec sed -i.bak 's/searchword/replace/g' "{}" +;
like image 181
ghostdog74 Avatar answered Oct 13 '22 13:10

ghostdog74


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'
like image 29
Legend Avatar answered Oct 13 '22 13:10

Legend