开发者

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.


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)


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

rpl -R Coke Pepsi .

(-R is for recursive replacement in all subdirectories)


Combine sed with find like this:

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


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


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


you want a combination of find and sed


You may also:

Search & replace with find & ed

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜