The following will replace the first comma on each line with a pipe:
How can I do the same for the last comma?
The best way to do this is to allow any character except for a newline,
. any number of times,
* followed by a comma
,. This gives us the following regex:
Or, the more readable way:
This works because
* is "greedy" by default, meaning it will match as many characters as possible.
An alternative, just for the sake of it :)
This can be translated as: go search (
s) on each line (
%) for any number of chars (
.*) followed by "a comma not followed by another one, i.e. followed by any other character, but comma" (
\ze around that one comma, we alter the match to only contain the character we want to act on. Therefore, the replacement part is simply the bar.
Edit/Update: of course, as Karl Yngve Lervåg mentions, the part after the comma isn't needed at all ..., so:
... is the better incantation.
Oh, I'll jump on the bandwagon. I can't resist a good regular expression question. :)
Since really what we're trying to find is a "comma with no commas after it," i propose we use a negative lookahead.
This matches a comma only if it does not have
.*, following it. However it only matches the comma since anything in a lookaround is only for context and not part of the match. Then we substitute it with a pipe, and our job is done.
I will prefer to go with a macro.
Go to line 1
qa to start recording in register
$ to move to end of line. Then,
/,<CR>N to search backwards for a comma. Then, press
r| to replace it with a bar. Press
j to move to next line. Press
@a to replay macro recursively. Then, stop macro by pressing
(In cade, if The macro runs infinitely at the last line of file. You can abort it by pressing Ctrl+C.)