[prog] replacement strings

Sam Watkins sam at nipl.net
Mon May 24 00:21:27 UTC 2010

On Mon, May 24, 2010 at 09:37:30AM +1000, Miriam English wrote:
> Does anybody know of anything (editor or shell command) which can find  
> and replace patterns like the following. I don't really care about  
> particular syntax, just so long as something exists that does the job.
> search pattern: \(foo[0-9]\)\(b[au]r\)
> replace pattern: \2 \1
> This searches for "foo" followed by a digit, then "bar" or "bur", then  
> replaces it with what it found, but in a different order -- in this case  
> "bar" or "bur" followed by "foo" and the digit that came after it.

You can do this with vim, emacs, sed, perl and many other tools.

example in vim:

  :%s/\(foo[0-9]\)\(b[au]r\)/\2 \1/gc

The "c" at the end is for "confirm", if you don't want that you can omit the
"c", or press "a" for "all" at the confirm prompt.

sed has the same syntax as vim.

  sed 's/\(foo[0-9]\)\(b[au]r\)/\2 \1/g' < infile > outfile

perl has a slightly different syntax:

  perl -pe 's/(foo[0-9])(b[au]r)/$2 $1/g' < infile > outfile

I don't recall how to do it in emacs.

It surprises me that you would know regexp syntax but not know how to use
regexps in any of these tools!  What do you use regexps for if not with these


More information about the Programming mailing list