Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

vim

vi

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?

like image 482
abeger Avatar asked Oct 20 '25 03:10

abeger


2 Answers

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).

like image 151
Andrew Clark Avatar answered Oct 22 '25 04:10

Andrew Clark


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

if I do this, I may do it with macro.

like image 36
Kent Avatar answered Oct 22 '25 05:10

Kent