5

I am looking for a shell script that recursively traverses all .php files in a directory and performs a search & replace of a particular text pattern.

The search pattern is quite long ( > 5000 characters) so it might be saved in another textfile for convenience. Also it contains forward slash characters.

edit: i think i figured out the first part:

find . -name "*.php"

but then how do i search & replace in those files?

3 Answers 3

8

It can be done easily with a good combination of sed and xargs.

find . -name "*.php" | xargs -n 1 echo

will show you the power of xargs.

After that, on a sample file, you can test the regexp, with an inplace change (-i) or a backup change (-i.bak). You can also use an other character to replace '/' if your pattern/replacement already have one.

At the end, it should looks like :

pattern=`cat /path/to/pattern`; replacement=`cat /path/to/replacement`
find . -name "*.php" | xargs -n 1 sed -i -e "s|$pattern|$replacement|g"
6
  • ok thank you! same question here: how would i load the search pattern from a file?
    – clamp
    Jan 17, 2012 at 9:52
  • 1
    something like this, maybe ? pattern=cat /path/to/pattern; replacement=cat /path/to/replacement; find . -name "*.php" | xargs -n 1 sed -i -e "s/$pattern/$replacement/g"
    – Coren
    Jan 17, 2012 at 10:04
  • thank you! the only problem remaining is that the pattern contains forward slashes which seem to be problematic in the regexp
    – clamp
    Jan 17, 2012 at 10:06
  • 1
    you can use an other character than '/' in sed. For instance, sed -i -e "|$pattern|$replacement|g works well
    – Coren
    Jan 17, 2012 at 10:15
  • thank you! now it runs without errors but it doesnt seem to replace anything. i guess the search pattern is not found. (although it is there). the search pattern contains all kind of characters including tabs, spaces, $, <, > etc. could that be the problem?
    – clamp
    Jan 17, 2012 at 10:22
5

Try:

find . -name "*.php" -exec sed -i "s/$(cat /path/to/pattern.txt)/$(cat /path/to/replacement.txt)/g" {} \;

where pattern is the pattern to search for and replacement is the text to replace it with.

The -i option for sed edits the files "in place". If you want to create a backup of the file before you edit it, use -i'.bak'.

2
  • thanks! how would i get pattern and replacement from a file?
    – clamp
    Jan 17, 2012 at 9:42
  • @clamp Replace the argument to sed by "s/$(cat /path/to/pattern.txt)/$(cat /path/to/replacement.txt)/g". Jan 17, 2012 at 23:39
0
perl -p -i -e 's/originalString/targetString/g' `find . -name '*' -type f`
1
  • Can you explain this?
    – George M
    Jan 18, 2013 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.