Vincent Lous
Vincent Lous

Reputation: 127

vim: replace word with first word of line

Problem
I have a file which looks like this:

word= something something aaa something aaa
word2= something something aaa something aaa
word3= something something aaa something aaa

Note that the "something " are not necessarily the same word everywhere. Also "something " and "aaa " are not necessarily separated by white spaces.

Question
I would like to replace all occurrences of "aaa" with the first word of the line within vim. The output should look like:

word= something something word something word
word2= something something word2 something word2
word3= something something word3 something word3

So far I have mainly looked into the search and replace syntax of vim, because that is what I am most familiar with.

Thank you for your help!

Upvotes: 2

Views: 749

Answers (2)

sidyll
sidyll

Reputation: 59307

For a solution entirely with regex, I suggest this:

:%s/\v%(^([^=]+).*)@<=aaa/\1/g

This works with a look behind (\@<=) which has zero width. The \v at the start of the regex is just to simplify escaping by enabling "very magic" mode (see :h \v). The expression itself:

%(^([^=]+).*)@<=aaa

The look behind operates with the first group. The %() form is a non capturing group (a bit faster, and won't count as a numbered one in the substitution). The inner group captures anything not a equal sign, and after this group, anything is matched (.*). All of this is not counted in the regex, what is really matched is the aaa, however it is only matched if preceded by those conditions. Of course it is preceded by them, but the goal is to capture the first word.

This aaa is then substituted by the captured group, multiple times in a line (g flag) and in all lines (% range).

Upvotes: 2

Kent
Kent

Reputation: 195259

This :s command works for your example:

%s/\<aaa\>/\=substitute(getline('.'),'^[^=]*\zs=.*','','')/g

Upvotes: 2

Related Questions