Tag: replace

Regular expressions: positive and negative lookaheads and lookbehinds

Do you work with regular expressions sometimes? If you do, and you don’t know about lookbehinds and lookaheads, you are missing out on a fantastic feature. I’m just pasting in something I said to some colleagues. Use your imagination and Google to extract the rest of the blog post 😉

[10/30/14, 10:11:44 PM] Kevin Kaland: man
[10/30/14, 10:11:53 PM] Kevin Kaland: lookaheads and lookbehinds in regex are awesome
[10/30/14, 10:11:58 PM] Kevin Kaland: I can’t believe I survived so long without them
[10/30/14, 10:12:46 PM] Kevin Kaland: you ever done a find/replace to change stuff like

nav.create
nav.formats-pricing

to

site.nav.create
site.nav.formats-pricing

and wound up accidentally with stuff like site.site.nav.create because you double-replaced?
[10/30/14, 10:13:07 PM] Kevin Kaland: if you use the regex (?<!site\.)nav\. for your find then this can’t happen
[10/30/14, 10:13:52 PM] Kevin Kaland: it won’t match it if it already has the site. in front. it’s called a negative lookbehind. negative meaning “it is not there” and lookbehind meaning that it checks before a particular string. there’s also positive look(ahead|behind)s, which make sure things are there.
[10/30/14, 10:14:08 PM] Kevin Kaland: but that text doesn’t become part of the actual match, which is the nice thing

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: http://www.linuxquestions.org/questions/linux-software-2/find-and-replace-text-in-multiple-file-203801/#post1742045

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.

Enjoy!

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.