Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim put quotes and comma around words

I Have a list of currencies in their abbreviations and long forms:

AED United Arab Emirates dirham
AFN Afghani
ALL Lek
AMD Armenian Dram
ANG Netherlands Antillian Guilder
AOA Kwanza
ARS Argentine Peso
AUD Australian Dollar
AWG Aruban Guilder
AZN Azerbaijanian Manat
BAM Convertible Marks
BBD Barbados Dollar
BDT Bangladeshi Taka
BGN Bulgarian Lev

I actually have 182 lines worth of them...in notepad++ I can easily in seconds get quotes around the individual words and commas after each word too, I was wondering whether there was a way to do this in vim or any other editor in Linux.

Even though I have already done it in notepad++ it would be nice to broaden myself to other editors too.

suggestions are much appreciated.

like image 354
user2405469 Avatar asked Jun 13 '14 16:06

user2405469


2 Answers

Try this command in ex mode.

%s/\w\+/"&",/g | $s/,$//

It should do the trick.

Explanation: %s substitutes on all lines

In the match portion:

\w is a "word character", which doesn't include spaces

\+ says to match one or more of the preceding character

In the replacement portion:

& refers to the entire matched string

Lastly, the g means to globally replace on the line, and not just stop the replacement after the first line.

The vertical bar | can be used to separate ex commands and run them in sequence.

$s refers to substituting on the last line. The substitution after the vertical bar will remove any commas at the end of the line, indicated by the $ anchor. This will make sure you don't have a trailing comma at the end of your list.

like image 60
benjwadams Avatar answered Sep 30 '22 20:09

benjwadams


One could record a macro:

gg
qq
I"<Esc>
f<space>
s","<Esc>
A",<Esc>
q

and execute it on every line:

:%norm @q<CR>

Or do the same thing in one go:

:%norm I"<C-v><Esc>f<space>s","<C-v><Esc>A",<C-v><Esc><CR>

Or, of course use a substitution:

:%s/\(\w\+\) \(.\+\)$/"\1","\2",
like image 45
romainl Avatar answered Sep 30 '22 19:09

romainl