user2836003
user2836003

Reputation:

Moving Columns/Text in VIM

I was wondering how I might go about moving around Columns/Text around in VIM using a string. I have a short list of names I have to reorder, which need to be placed in Last Name First Middle to First Middle Last.

So here would be an example list:

I was thinking that the string should look something like this:

:s/\([A-z]\{2}\)\(\[A-z]\{2}\)/2\1/

Thanks

Upvotes: 0

Views: 108

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270637

First, I recommend using the \v "very magic" flag to avoid all the other internal escaping of metacharacters. This will work with a replacement like:

 :s/\v([A-z]+),\s+([A-z]+)(\s+[A-z.]+)?/\2\3 \1

Breaking it down:

  • ([A-z]+) Capture the last name into \1
  • ,\s+ A literal comma and one or more spaces
  • ([A-z]+) Capture the first name into \2
  • (\s+[A-z.]+)? Capture the middle name with its leading spaces, since it may not exist. Also permit the ., and end with a ? to make the whole construct optional, into \3
  • \2\3 \1 Replace with the second group (first name) followed immediately by the middle name \3 with no space in between because the space was captured along with the middle name. Then append \1 the last name.

If the names could be possibly more than [A-z]+, you may alternatively use [\S]+ to capture all non-whitespace characters.

Upvotes: 3

Ingo Karkat
Ingo Karkat

Reputation: 172600

How about this:

:%s/\([[:alpha:]]\+\), \([[:alpha:]]\+\)\( [[:alpha:]]\+\.\?\)\?/\2\3 \1/g

This captures last, middle (optional), and first, and reorders them in the replacement. You'll probably need to include additional characters in the [[:alpha:]] collection, but this works for your example.

For more information, learn how the excellent and comprehensive :help is structured; all the information is in there (you just need to know how to find it)! There are also many very similar regular expression questions here on Stack Overflow.

Upvotes: 0

Related Questions