vphomealone
vphomealone

Reputation: 163

Shell script to recursively browse a directory and replace a string

I need to recursively search directories and replace a string (say http://development:port/URI) with another (say http://production:port/URI) in all the files where ever it's found. Can anyone help?

It would be much better if that script can print out the files that it modified and takes the search/replace patterns as input parameters.

Regards.

Upvotes: 3

Views: 4467

Answers (5)

Bernd
Bernd

Reputation:

Don't try the above within a working SVN / CVS directory, since it will also patch the .svn/.cvs, which is definitely not what you want. To avoid .svn modifications, for example, use:

find . -type f | fgrep -v .svn | xargs sed -i 's/pattern/replacement/g'

Upvotes: 1

Zsolt Botykai
Zsolt Botykai

Reputation: 51693

Use zsh so with advanced globing you can use only one command. E.g.:

sed -i 's:pattern:target:g' ./**

HTH

Upvotes: 0

toolkit
toolkit

Reputation: 50297

Try this:

find . -type f | xargs grep -l development | xargs perl -i.bak -p -e 's(http://development)(http://production)g'

Another approach with slightly more feedback:

find . -type f | while read file
do
    grep development $file && echo "modifying $file" && perl -i.bak -p -e 's(http://development)(http://prodution)g' $file
done

Hope this helps.

Upvotes: 5

indentation
indentation

Reputation: 10025

find . -type f | xargs sed -i s/pattern/replacement/g

Upvotes: 6

Jay Bazuzi
Jay Bazuzi

Reputation: 46546

It sounds like you would benefit from a layer of indirection. (But then, who wouldn't?)

I'm thinking that you could have the special string in just one location. Either reference the configuration settings at runtime, or generate these files with the correct string at build time.

Upvotes: 2

Related Questions