0

I have the following lines:

abc07
bca08
xyz17

And I would like to transform it to:

    [0]="abc07" \
    [1]="bca08" \
    [2]="xyz17" \

Based on this question, I can do the first part and the end part separately, like this:

FIRST PART

:let i=0 | g/^/execute "normal! I" . printf("^I[%d]=\"", i) | let i+=1

OR

:let i=0 | g/^/s/^/\=printf("^I[%d]=\"", i)/ | let i+=1

SECOND PART

:%s/$/\"\ \\/g

But I am unable to combine these two in the same command. (Yes, I know, I overcomplicate things...) Can you help me out to combine the two parts in one command? An entirely different solution is also OK for me.

  • Do you want help specifically combining the two commands, or would an entirely different solution be OK? – DJMcMayhem Sep 26 '18 at 15:00
  • An entirely different solution is also OK, I just wanted to explain how I tortured myself:) – Aba Sep 26 '18 at 15:03
3

If you want to do this with a single command, I would recommend the following:

:%s/.*/\='    ['.(line('.')-1).']="'.submatch(0).'" \'

This uses the \= to evaluate the following strings joined together (remember, '.' means concatenation in vimscript):

'    ['
(line('.')-1)
']="'
submatch(0)
'" \'

line('.') returns the current line number, and submatch(0) is like \0 in regex (it captures the entire text).

However, if I were the one editing this, I'd probably do it in normal mode (assuming vim 7.4+). For example:

<C-v>GI    [-1]="<esc>gvwwg<C-a>gv$A" \<esc>

Rather than explaining each part of this, it would be easier to just type these out and see the effects.

Of course, neither of these solutions will work if you are trying to do this to only certain lines in the buffer, rather than the whole thing. In that case, you could modify each one. For example, the first one could be modified by changing :% to :a,b, where a and b are you start/end lines. And then change line('.')-1 to line('.')-a.

The second solution would just require changing your visual block selection, so not using gg or G.


As a side note,

g/^/s/^/\=printf("^I[%d]=\"", i)/

is unnecessary because :g/^/s/^ is exactly the same as :%s/^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.