Tip 94 | Rearrange CSV Fields Using Submatches |
In this tip, we’ll see how submatches captured from the search pattern can be referenced in the replacement field.
Let’s say that we have a CSV file containing a list of email addresses along with first and last names:
| last name,first name,email |
| neil,drew,drew@vimcasts.org |
| doe,john,john@example.com |
Now suppose that we want to swap the order of the fields so that the email comes first, then the first name, and finally the last name. We could use this substitute command to do it:
=> | /\v^([^,]*),([^,]*),([^,]*)$ |
=> | :%s//\3,\2,\1 |
In the pattern, [^,] matches anything that isn’t a comma. So ([^,]*) matches zero or more consecutive non-commas and captures the result ...
Get Practical Vim, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.