Bash: any command to replace strings in text files

2019-05-13 21:04发布

问题:

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.

回答1:

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)



回答2:

Combine sed with find like this:

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


回答3:

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

rpl -R Coke Pepsi .

(-R is for recursive replacement in all subdirectories)



回答4:

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



回答5:

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;' {} \;


回答6:

you want a combination of find and sed



回答7:

You may also:

Search & replace with find & ed

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

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