Reputation: 3512
I have a Java Class
public class Constants{
public static final MyClass field1 = new MyClass("arg1"); // line 10
public static final MyClass field2 = new MyClass("arg2");
...
public static final MyClass field101 = new MyClass("arg101"); //line 100
}
I want the 5th word of each line to be appended as the second argument of MyClass
's constructor As:
public class Constants{
public static final MyClass field1 = new MyClass("arg1", "field1"); // line 10
public static final MyClass field2 = new MyClass("arg2", "field2");
...
public static final MyClass field101 = new MyClass("arg101", "field101"); //line 100
}
To simplify, lets not care about the ");
s at the end of each line.
How can I put the fifth word from line 10 to line 100 to the end of each line with a vim command?
Upvotes: 2
Views: 1363
Reputation: 5861
Try this:
:10,100s/\v^%(\s*\w+){4}\s+(\w+).*\zs\ze\)/, "\1"/
Edit: spelling it out:
:10,100
- apply to lines 10 -- 100s/.../.../
- substitute\v
- change regexp syntax to "very magic", so we can write %(...)
, {...}
, and +
instead of \%(...\)
, \{...}
, and \+
^
- anchor at beginning of line%(...)
- non-capturing group; identical to (...)
, except it doesn't create a backreference (that is, it doesn't add anything to \1
, \2
, ..., \N
)\s*\w+
- spaces + word{4}
- repeat last item 4 times; that is, skip first four words\s+
- skip spaces(\w+)
- capture next word in \1
.* ... \)
- skip to last parenthesis; )
becomes \)
because of \v
\zs
- start replacing here; match everything, but replace only the part to the right of \zs
\ze
- end replacing here; match everything, but replace only the part to the left of \ze
/, "\1"/
- insert , "foo"
; \1
comes from (\w+)
, and since we have \zs
and \ze
next to each other, the effect is to replace the empty string at that point with , "foo"
.Upvotes: 4
Reputation: 196866
:10,100normal! 0f=byiwf)i, "<C-v><C-r>""<CR>
In English:
10
to line 100
,=
,, "
,"
.The whole thing could be done with a recording, of course:
qq
0f=byiwf)i, "<C-r>""<Esc>
q
:10,100norm! @q
Upvotes: 4