开发者

Easiest way to recursively find and replace?

开发者 https://www.devze.com 2022-12-25 10:40 出处:网络
I want to recursively search through a directory of text files and replace every occurrence of foo within the file开发者_C百科s with bar.What is the easiest way to accomplish this?

I want to recursively search through a directory of text files and replace every occurrence of foo within the file开发者_C百科s with bar. What is the easiest way to accomplish this?

I imagine that grep would do the job in one line, but I can't seem to find an example of this.

I'm working in OS X.


GNU find

find /path -type f -iname "*.txt" -exec sed -i.bak 's/foo/bar/g' "{}" +;


grep is only used to find things, not to modify them.

For modifications with a grep-like interface, you'd typically use sed. By itself, sed doesn't support any kind of recursion though -- it only operates on one file at a time. To add that, you normally use find to find the files to contain the desired pattern, then have it invoke sed to modify the file.


zsh

sed -i 's/foo/bar/g' **/*.txt


try this: grep -rl "foo" .|xargs sed -i 's/foo/bar/g'


There's a nice free text editor that will do this kind of thing simply and easily: TextWrangler.

0

精彩评论

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

关注公众号