Find and Replace Strings in Files

The Wikipedia article on find is great.

Searching

To check for the existence of the string in any of the files in the directory structure:

find . -exec grep -H “searchstring” ‘{}’ \; -print

On Solaris ommit the ‘-H’.
or using grep only:

grep -r “searchstring” /tmp

Replacing

Find in the current directory (.) type file then execute a sed inline and replace ‘fromstring’ with ‘tostring’:

find . -type f -exec sed -i ‘s#fromstring#tostring#’ {} \;

On Solaris I found it necessary to explicitly point to the gnu sed:

find . -type f -exec /usr/local/bin/sed -i ‘s/fromstring/tostring/’ {} \;

The normal convention is to use ‘/’ as the sed delimiter but other characters can be used.
It will also be necessary to escape regular expression characters in the sed statement so a forward slash ‘/’ would need escaped to ‘\/’. Other characters which may need escaping

. * [ ] ^ $ \

Leave a Reply

  • (will not be published)

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