I have the following strings (whitespace and line wise separated) in a file

mks asksö askndl
ebre nakkl sadj

and would like to have it formatted as follows

["mks", "asksö", "askndl"],
["ebre", "nakkl", "sadj"],

What shortcut sequence is suitable?

  • You could do a substitute to surround the words, and then use global to put in the brackets
    – D. Ben Knoble
    Nov 23 '18 at 15:08
  • I am fairly new to vim. Could you give me more hints?
    – thinwybk
    Nov 23 '18 at 15:10
  • 1
    Ill put together an answer later
    – D. Ben Knoble
    Nov 23 '18 at 15:10
  • :s and :g are overwhelming a bit right now :) Thx
    – thinwybk
    Nov 23 '18 at 15:14

Since @LucHermitte alluded to a macro-based solution, I thought I'd provide one.


First line adds in the quotes and commas, the second line adds the brackets.

(N.B. in the above, <C-R> means press Ctrl-R, <Esc> means press Esc, and <BS> means press Backspace.)

I could write a long explanation of how this works but honestly, it will be quicker and easier for you just to try typing it in. If you're still not sure what's happening, you might need to read up on recursive macros and :help i_CTRL-R.

Note that this is not remotely VimGolf'ed. I've no doubt the good people at vimgolf.com could come up with a solution that did the same thing in a quarter of the keystrokes.


There are so many ways to proceed...

  • the simple 2-steps solution

    :%s/\s\+/', '/g
  • or, in one step

    :%s/.*/\="['".substitute(submatch(0), '\s\+', "', '", 'g')."'],"
  • or also

    :%s/.*/\=string(split(submatch(0), '\s\+')).','
  • or, my preferred one (in Vim script contexts)

    :call setline(1, map(getline(1,'$'), 'string(split(v:val, "\\s\\+")).","'))

And I'm quite sure that macros-oriented-people could VimGolf this problem in very few key strokes

  • Using string(split()) is terrific (I was trying to figure out how I could get the output displayed when you :echo a list), but--correct me if I'm wrong--doesn't it result in text with single quotes instead of double quotes?
    – Rich
    Nov 23 '18 at 17:25
  • Also, I think you're missing the final end-of-line comma in all of these.
    – Rich
    Nov 23 '18 at 17:25
  • @Rich. You're right, twice. 1. string(list) will always produce single quotes, AFAIK. 2. I've forgotten the final comma. Nov 23 '18 at 17:28
  • Also, sometimes ago I had the singular idea of writing my own stringification function, but internally I also use string() for strings and functions. I could use something else in order to surround with double-quotes. Nov 23 '18 at 17:31

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.