42

How do i find and replace a string on command line in multiple files on unix?

Vijay
  • 65,327
  • 90
  • 227
  • 319
  • possible duplicate of [Find and replace a particular term in multiple files](http://stackoverflow.com/questions/2263925/find-and-replace-a-particular-term-in-multiple-files) – Quanlong Jun 11 '15 at 15:35

5 Answers5

50

there are many ways .But one of the answers would be:

find . -name '*.html' |xargs perl -pi -e 's/find/replace/g'
Vijay
  • 65,327
  • 90
  • 227
  • 319
37

Like the Zombie solution (and faster I assume) but with sed (standard on many distros and OSX) instead of Perl :

find . -name '*.py' | xargs sed -i .bak 's/foo/bar/g'

This will replace all foo occurences in your Python files below the current directory with bar and create a backup for each file with the .py.bak extension.

And to remove de .bak files:

find . -name "*.bak" -delete
Stan
  • 8,710
  • 2
  • 29
  • 31
7

I always did that with ed scripts or ex scripts.

for i in "$@"; do ex - "$i" << 'eof'; done
%s/old/new/
x
eof

The ex command is just the : line mode from vi.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
6

Using find and sed with name or directories with space use this:

find . -name '*.py' -print0 | xargs -0 sed -i 's/foo/bar/g'
XavierCLL
  • 1,163
  • 10
  • 12
2

with recent bash shell, and assuming you do not need to traverse directories

for file in *.txt
do
while read -r line
do
    echo ${line//find/replace} > temp        
done <"file"
mv temp "$file"
done 
ghostdog74
  • 327,991
  • 56
  • 259
  • 343