Vim: How can I search and replace only part of each line?

I have a list of phrases with spaces:

Part One
Part Two
Parts Three And Four

I would 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 use this regex:

:%s/.*/\L\0\E,"\0"/

to get me to this that is really close:

part one,"Part One"
part two,"Part Two"
parts three and four,"Parts Three And Four"

Is there a way to replace all spaces before the comma on each with underscores? Or as a modification of the above regular expression or as a second command?

+3
source share
4 answers

Assuming there are never commas in your source data, you should be able to use the following:

:%s/.*/\L\0\E,"\0"/ | %s/ \([^,]*,\)\@=/_/g

This is just another substitution after your current one to replace all the spaces that appear before the comma (using a positive view).

+4
:g/./let @s='"'.getline('.').'"'|s/ /_/g|exec "norm! guuA,\<ESC>\"sp"

, .

+1

, :

:%s/\v^.*$/\=tolower(substitute(submatch(0), "\\s\\+", "_", "g")) . ",\"" . submatch(0) . "\""/

_, - . , .

:

part_one,"Part One"
part_two,"Part Two"
parts_three_and_four,"Parts Three And Four"
0

From where you left off, I would split all the lines after the decimal point:

:%s/,/,\r/

Then you can replace the spaces only with lines with a comma and combine your lines:

:g/,/:s/ /_/g|j!
0
source

All Articles