Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Replace all dots but the last one in a line

Tags:

vim

I'm looking for a way to replace all dots in a line except the last one.

Example:

Blah - whatever - foo.bar.baz.avi should become
Blah - whatever - foo bar bar.avi

Since I'll have more than one line in the file and the amount of dots varies in each line I'm looking for a generic solution and not something like "Replace the first X matches" with X being a constant.

like image 353
ThiefMaster Avatar asked Jun 03 '12 12:06

ThiefMaster


People also ask

How to replace all occurrences Vim?

In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.

How to replace all occurrences of a string in Vi editor?

Press y to replace the match or l to replace the match and quit. Press n to skip the match and q or Esc to quit substitution. The a option substitutes the match and all remaining occurrences of the match. To scroll the screen down, use CTRL+Y , and to scroll up, use CTRL+E .

How to change all occurrences of a word in Vi?

The % is a shortcut that tells vi to search all lines of the file for search_string and change it to replacement_string . The global ( g ) flag at the end of the command tells vi to continue searching for other occurrences of search_string . To confirm each replacement, add the confirm ( c ) flag after the global flag.


2 Answers

This seems to do the trick:

%s/\.\(.*\.\)\@=/ /g

\@= is a lookahead. It only matches a full stop if there are any following full stops.

See :help zero-width.

like image 83
Felix Kling Avatar answered Nov 22 '22 14:11

Felix Kling


As a variation on the first answer you may prefer this syntax:

%s/\.\ze.*\./ /g

It let's you put the assertion that there be a following full stop after the search operator.

like image 24
gordyt Avatar answered Nov 22 '22 14:11

gordyt