Find & Replace in Files on Linux

12:28 pm Code Monkey

TuxA lot of solutions I’ve found for recursively replacing text in files is implemented using shell scripts, perl, php, or some other inconvenient way. Rushi got it right by using the Linux command line. Here it is (slightly modified) from his blog:

find . -name “*.cpp” -print | xargs sed -i ’s/[find]/[replace]/g’

where “[find]” and “[replace]” are the things you are searching for and substituting.

To search files with multiple file extensions, use:

find . -name “*.cpp” -o -name “*.h” -o -name “*.c” | xargs sed -i ’s/[find]/[replace]/g’

ADDED 4-13-2009: See comments for other variations.

2 Responses

  1. Steve Mitchell Says:

    Back when I actually worked for a living, I was always fond of the “exec” argument to find for this type of work. Will this suffice?

    find . -name “*.cpp” -exec sed -ie ’s/[find]/[replace]/g’ {} \; -print

    [Reply]

  2. Rushi Says:

    Steve,

    exec works well too, but it’s slower than using xargs

    [Reply]

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.