Reputation: 6866
I've got a list of phrases with spaces:
Part One
Part Two
Parts Three And Four
I'd like to use Vim to process the list to produce this:
part_one,"Part One"
part_two,"Part Two"
parts_three_and_four,"Parts Three And Four"
I can get use this regex:
:%s/.*/\L\0\E,"\0"/
to get me to this, which is really close:
part one,"Part One"
part two,"Part Two"
parts three and four,"Parts Three And Four"
Is there any way to replace all spaces before the comma on each with underscores? Either as a modification of the above regex or as a second command?
Upvotes: 4
Views: 132
Reputation: 378
You can use as second command:
:%s/\(\(,.*\)\@<=\)\@! /_/g
\(\(,.*\)\@<=\)\@!
inversely match ,"Part One"
, ,"Part Two"
...
Also:
:%s/ \(.*"..*\)\@=/_/g
Upvotes: 0
Reputation: 16
From where you left off, I would split all the lines after the comma:
:%s/,/,\r/
Then you can replace the spaces on just the lines with a comma and join your lines back together:
:g/,/:s/ /_/g|j!
Upvotes: 0
Reputation: 195029
:g/./let @s='"'.getline('.').'"'|s/ /_/g|exec "norm! guuA,\<ESC>\"sp"
if I do this, I may do it with macro.
Upvotes: 1
Reputation: 36252
You can try with an expression in the replacement part, like:
:%s/\v^.*$/\=tolower(substitute(submatch(0), "\\s\\+", "_", "g")) . ",\"" . submatch(0) . "\""/
It first substitute all whitespaces with _
, and the returned string is lowercased. Then it joins the result with the matched line surrounded with double quotes.
It yields:
part_one,"Part One"
part_two,"Part Two"
parts_three_and_four,"Parts Three And Four"
Upvotes: 0
Reputation: 208405
Assuming there will never be commas in your original data, you should be able to use the following:
:%s/.*/\L\0\E,"\0"/ | %s/ \([^,]*,\)\@=/_/g
This just does another replacement after your current one to replace all of the spaces that come before a comma (using a positive lookahead).
Upvotes: 4