Tuesday, March 10, 2009

Change Last, First to First Last

Here's a tip borrowed from the Vim help file. Say that you have a list of names like:

Doe, John
Smith, Peter

and you want to change that to:

John Doe
Peter Smith

You can use the following substitute pattern to easily do so:

:%s/\([^,]*\), \(.*\)/\2 \1/

Basically, you're capturing zero or more NOT commas followed by a comma and space and then capturing zero or more of anything. The comma and space are outside the parens, so they're not stored. The parens store the captured groups in the special variables \1, \2, \3, \N from left to right, so the replacement pattern is substituting in the groups in the reverse order they were captured.


Kent said...

That one trashes the commas (it's must have been a copy paste error?) and requires an exact formatting with a comma first and followed by a single space.

Here is my take on it:

:%s/\([^,]*\)\([ \t]*,[ \t]*\)\(.*\)/\3\2\1/

Try it on:
One, Onespace
Two, Twospaces

It's nice if you want to keep the original formatting and not depend on white space around the comma.

Kent said...

s/it's/it ... I wish I could edit comments. :-)

carlosp said...

Funny, I needed that just a couple of days ago, and had to ask for some help :P

Kent said...

Reading it again. I see that you wanted the commas removed. Well, I didn't. ;-)

Greg said...

The 'delimiter negation' such as [^,]* is something I find myself using all the time. It almost merits it's own syntax. I've often used this: "\([^"]*\)" which is a great way to avoid over-greediness for a delimited subexpression like that.