Find & Replace in Files on Linux

On April 13, 2009, in Code Monkey, by Tom

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.

Tagged with:  

2 Responses to Find & Replace in Files on Linux

  1. 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 Reply

Your email address will not be published. Required fields are marked *

*

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