Linux tip – regular expression find and replace in all files in a directory

As you may have seen me tweet, I’ve been looking for a way to do this. I didn’t want to manually change my Apache configuration to reflect my new internal IP address. After some Internet searching, I stumbled across this gem:

find . -name '[^.]*' | xargs perl -pi -e 's/192\.168\.1\.3/192\.168\.0\.3/g'

I adapted it to this for my task of replacing IP addresses. The first set of numbers is the old one (don’t delete the backslashes) and the second set is the new one.

This command assumes all files in the directory are configuration files and do not start with a dot.


Update: According to a commenter, sed -i 's/thisip/thatip/g' * should also work. I didn’t try that since I thought it wouldn’t work with multiple input files.