3

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.

1
  • What platform? What languages will you accept? Commented Sep 23, 2008 at 22:49

5 Answers 5

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

an extra note: you have to escape quotation marks with backslashes in the pattern: ... sed -i s/\"hello\"/hi/g
results in invalid command code ...... the farthest I got was with this: find iPhone_Src/ -type f | xargs sed -i '' -e's/__MyCompanyName__/Samsung Electronics, Inc./g'.... but even that does the job only half way, giving sed: iPhone_Src//GUI: in-place editing only works for regular files..... Listing: find iPhone_Src/ -type f | xargs grep -1 -C 0 Copyright 2>/dev/null | grep -v Samsung | head Binary file iPhone_Src//image/demo_bt_feedback.png matches iPhone_Src//main.m:// Copyright __MyCompanyName__ 2010. All rights reserved. etc. etc.
5

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.

1 Comment

Note that the old files will be saved as *.bak, which indirectly satisfies the requirement: "print out the files that it modified".
2

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.

Comments

1

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'

Comments

0

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

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

HTH

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.