0

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?

statox
  • 49,782
  • 19
  • 148
  • 225
thinwybk
  • 101
  • 2

2 Answers2

2

There are so many ways to proceed...

  • the simple 2-steps solution

    :%s/\s\+/', '/g
    :%s/.*/['&'],/
    
  • 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

Luc Hermitte
  • 17,351
  • 1
  • 33
  • 49
  • 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. – Luc Hermitte 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. – Luc Hermitte Nov 23 '18 at 17:31
2

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

qqqqqciw"<C-R>"",<Esc>w@qq@q
qqqqqi]<Esc>I[<Esc><BS>@qq@q

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.

Rich
  • 31,891
  • 3
  • 72
  • 139