How to search and replace text in all php-files in a directory and it's subdirectories

8,230

Solution 1

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"

Solution 2

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'.

Share:
8,230

Related videos on Youtube

clamp
Author by

clamp

hello, i am looking for a job as an android programmer

Updated on September 18, 2022

Comments

  • clamp
    clamp almost 2 years

    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?

  • clamp
    clamp over 12 years
    thanks! how would i get pattern and replacement from a file?
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' over 12 years
    @clamp Replace the argument to sed by "s/$(cat /path/to/pattern.txt)/$(cat /path/to/replacement.txt)/g".
  • George M
    George M over 11 years
    Can you explain this?