Elias Zamaria
Elias Zamaria

Reputation: 101073

Bash: any command to replace strings in text files?

I have a hierarchy of directories containing many text files. I would like to search for a particular text string every time it comes up in one of the files, and replace it with another string. For example, I may want to replace every occurrence of the string "Coke" with "Pepsi". Does anyone know how to do this? I am wondering if there is some sort of Bash command that can do this without having to load all these files in an editor, or come up with a more complex script to do it.

I found this page explaining a trick using sed, but it doesn't seem to work in files in subdirectories.

Upvotes: 4

Views: 3938

Answers (7)

eddie
eddie

Reputation: 1

You may also:

Search & replace with find & ed

http://codesnippets.joyent.com/posts/show/2299

(which also features a test mode via -t flag)

Upvotes: 0

ebal
ebal

Reputation: 375

find . -type f -exec sed -i 's/old-word/new-word/g' {} \;

Upvotes: 3

Chris Lercher
Chris Lercher

Reputation: 37778

IMO, the tool with the easiest usage for this task is rpl:

rpl -R Coke Pepsi .

(-R is for recursive replacement in all subdirectories)

Upvotes: 4

user177800
user177800

Reputation:

you want a combination of find and sed

Upvotes: 2

Ricardo Marimon
Ricardo Marimon

Reputation: 10687

Combine sed with find like this:

find . -name "file.*" -exec sed -i 's/Coke/Pepsi/g' {} \;

Upvotes: 3

Maja Piechotka
Maja Piechotka

Reputation: 7216

I usually do it in perl. However watch out - it uses regexps which are much more powerful then normal string substitution:

% perl -pi -e 's/Coke/Pepsi/g;' $filename

EDIT I forgot about subdirectories

% find ./ -exec perl -pi -e 's/Coke/Pepsi/g;' {} \;

Upvotes: 2

Yann Ramin
Yann Ramin

Reputation: 33187

Use sed in combination with find. For instance:

find . -name "*.txt" | xargs sed -i s/Coke/Pepsi/g

or

find . -name "*.txt" -exec sed -i s/Coke/Pepsi/g {} \;

(See the man page on find for more information)

Upvotes: 15

Related Questions