user2829759
user2829759

Reputation: 3512

Vim - Copy Nth word of each line, from line 10-100, to end of line

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

Answers (2)

lcd047
lcd047

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 -- 100
  • s/.../.../ - 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

romainl
romainl

Reputation: 196866

:10,100normal! 0f=byiwf)i, "<C-v><C-r>""<CR>

In English:

  • from line 10 to line 100,
  • execute the following normal command without caring for remappings,
  • go to the first column of the line,
  • jump to the first =,
  • go back one word,
  • yank that word,
  • jump to the first closing parenthesis,
  • enter insert mode before the parenthesis,
  • insert , ",
  • followed by the content of the unnamed register (the word we yanked before),
  • followed by ".

The whole thing could be done with a recording, of course:

qq
0f=byiwf)i, "<C-r>""<Esc>
q
:10,100norm! @q

Upvotes: 4

Related Questions