find and replace in multiple files on command line

38,629

Solution 1

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

find . -name '*.html' |xargs perl -pi -e 's/find/replace/g'

Solution 2

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

Solution 3

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.

Solution 4

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

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

Solution 5

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 
Share:
38,629
Vijay
Author by

Vijay

http://theunixshell.blogspot.com/

Updated on July 09, 2022

Comments

  • Vijay
    Vijay almost 2 years

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

  • Chris Foulon
    Chris Foulon about 11 years
    This affects whitespace outside of the search. It seemed to add new lines to the end of each of my files.
  • al45tair
    al45tair about 11 years
    AFAIK in-place editing is not supported in every version of sed; I think it's a GNU extension.
  • al45tair
    al45tair about 11 years
    This has the distinct advantage that you can perform more sophisticated edits.
  • friedemann
    friedemann almost 10 years
    it's a gnu extension and at least in my version it has to be sed -i.bak (no space)
  • mvallebr
    mvallebr about 9 years
    my version works with -i without needing to specify .bak extension
  • swpalmer
    swpalmer almost 9 years
    This fails if you have a folder named ".py"
  • Seán Hayes
    Seán Hayes about 6 years
    This will only touch files and won't generate .bak files: find . -type f -name '*.py' | xargs sed -i"" 's/foo/bar/g'