Logo Background

Find, Search And Replace Files In UNIX

  • By on February 13, 2009 | No Comments

    Do you know how to search and replace in all files within a directory recursively on Unix?

    This command below will search recursively through directories, looking in all the files for a particular string, and to replace that string with something else on UNIX:

    find . -name "*.c" -exec sed -i "s/oldWord/newWord/g" '{}' ;

    Remember that sed -i will update the search and replace string in the file on the spot. You can’t rollback your action, so please make sure you have a backup on those files.

    Example:

    I would like to change the string “/prod/appl” to “/test/dev” in all the XML file in the current location

    find ./ -name "*.xml" -type f -exec sed -i 's//prod/appl//test/dev/g' {} ;

    or

    find ./ -name "*.xml" -type f -exec sed -i 's:/prod/appl:/test/dev:g' {} ;

    or

    It would have been better to use xargs instead of -exec. Using xargs, you will fork fewer times. For large numbers of files, that means you will be done faster. In other words:

    find ./ -name "*.xml" -type f | xargs sed -i 's:/prod/appl:/test/dev:g'

    Bear in mind not all the sed -i option was supported in the UNIX platform especially in HPUX, maybe is due to security reason.

    Previous
    Next
    » Enable Trace On Concurrent Program
Leave a Comment