Results 1 to 4 of 4
  1. #1

    Replace string in all files in a folder

    I have more than 500 .php files in a folder.

    These files have a file path inside it, like

    $path = "/home/username/public_html/uploads/";

    Recently i have changed the site to another server, in the new server, the path is different, so i need to change all $path variables to

    $path = "/home/myfolder/uploads/";

    New server OS is FreeBSD 5.3.

    All php files are in a folder


    How i make the changes in all PHP Files ?

  2. #2
    Look up grep, I am pretty sure you should find some options.

    Then, once you have... consider making it include a config, and have the pathname in there.

  3. #3
    Join Date
    Mar 2005
    Cardiff, Wales, UK
    grep is the GNU Regular Expressions Program. It's fine for searching for lines, but not for replacing or modifying.

    The program your after is sed. A small script like:

    for file in $(find -type f -iname '*.php')
      cp "$file" "$(dirname "$file")/$(basename "$file" .php).bak"
      cat "$file" | sed 's%old%new%' > "$(dirname "$file")/$(basename "$file" .php).new
      mv -f "$(dirname "$file")/$(basename "$file" .php).new" "$file"
      echo "done "$file
    where 's%old%new%' is a regular expression for substitution.

    I haven't tried this code - just written it here, but it should pretty much work. It'll also create a backup file (i.e. ./path/to/file.php is copied to ./path/to/file.bak). Also, sed can't read a file and have the console write to it as well. Causes all sorts of problems, so you need to redirect the output to another file and then mv the file back.
    Jonathan Wright (Technical Director, JAB Web Solutions Limited).

    UK Hosting and Reseller Hosting from JAB Web Solutions

  4. #4
    Run this in shell:

    cd /path/to/config/
    perl -pi -e 's,/home/username/public_html/uploads/,/home/myfolder/uploads/,' *
    Like us on Facebook to qualify for discounts!
    Offering: | Internap FCP Bandwidth! | Rebootless Kernel Updates! | Magento Optimized Hosting | Wordpress Hosting |
    Services: | Managed Multiple Cores 64bit Servers | Server Management |

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts