CA BD NY
  • Categories

  • Recent Posts

  • RSS MySQL Hacker

  • RSS Apache Hacker

  • RSS MiniCTO

  • Meta

  • Global Search and Replace Using the fgres Utility

    Published November 5th, 2008

    Problem Statement

    Often we need to replace strings in lots of files and find it very useful to use a utility called fgres, which is not a standard tool for CentOS. However, it is extremely easy to compile and install on a CentOS system. Here we will show you how to setup fgres on your system and show some example usage.

    Installing fgres

    Follow the steps below:

    • Download fgres from the Web by searching for it on Google. For example, you can download it from:
      http://www.sfr-fresh.com/unix/misc/fgres-1.5.tar.gz
    • Extract the source in /usr/local/src and you should see a new sub-directory called fgres-[version] (example: fgres-1.5)
    • Change directory to the new fgres sub directory
    • Run: make
    • Once make is successful, copy the fgres binary to /usr/bin/fgres

    Now you have fgres in your standard path and can access it as you do with any other standard utility.

    Using fgres to search and replace strings in files

    To replace a string called ‘WRONG’ with ‘RIGHT’ in every HTML file inside a Web directory called /var/data/htdocs, you can run the following command from the /var/data/htdocs directory:

    find . -type f -name "*.html"  -exec fgres 'WRONG' 'RIGHT' {} \;
    

    This will change every occurrence of the word ‘WRONG’ with ‘RIGHT’ in every file with .html extension inside the /var/data/htdocs and all its sub directories.

    To replace ‘www.oldsite.com’ with ‘www.newsite.com’ in a single HTML/text file called index.html, you can run:

    fgres 'www.oldsite.com'  'www.newsite.com'  index.html
    

    Get a Trackback link

    1 Comments

    1. Amos on February 17, 2009

      Personally I find myself doing a lot of:
      sed -r -i~ -e ’s/regexp/new-value/g’
      You can combine this either with a shell wildcard file name or attach it to the end of a find … | xargs, e.g.:
      find -name \*.xml | xargs sed -r -i~ -e ’s/\b192\.168\.0\.0\b/74.54.67.89/g’

      The -r switched to extended regexp’s, the -i~ keeps a backup copy before changing the file, so you can compare and revert if you find an error.

    Leave a comment

    Comment Policy: First time comments are moderated. Please be patient.