11

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".

5 Answers 5

15
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' "{}" +;
3
  • The second option can be shortened to sed -i.bak '/searchword/s//replaceword/g' Feb 15, 2010 at 4:08
  • the second option traverse subdirectories.
    – ghostdog74
    Feb 15, 2010 at 5:26
  • 1
    @ghostdog: You miss the point of my comment. With sed, you do not need to specify the searchword twice. Feb 16, 2010 at 22:18
12

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'
7
  • You can also just do sed 's<searchthis>/<replacewith>/g' -i *
    – JAL
    Feb 15, 2010 at 3:35
  • Ah... even simpler.. :) Thanks!
    – Legend
    Feb 15, 2010 at 3:40
  • 1
    @Code Duck - this will avoid invoking sed where there is no search term present. More efficient - I guess - when the files are large. Feb 15, 2010 at 3:41
  • @ Tom Duckering : I thought of that too, but then realized the first example is greping through each file in the directory to find the term, too. Sed may or may not be as efficient as grep at doing that, but anyhow it seems simpler to just use one command.
    – JAL
    Feb 15, 2010 at 4:13
  • @Code Duck - yeah - the usual trade one makes in adding complexity to make something more efficient. :) Feb 15, 2010 at 4:25
2

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; done
1,$s/searchword/replaceword/g
w
q
eof
0

This ruby script worked for me, also renames the files/folders with that typo in too.

0

Try mffr if you are in a git repo

pip install mffr
mffr searchword replaceword

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.