keala
keala

Reputation: 387

How to insert a word/text in front of every "string" in vim and remove quotation marks

I have strings like this in my file: case field == "first_name" || field == "last_name" and I'd like to remove the quotations marks and put the text constants. in front of all of them.

This is the end goal: case field == constants.first_name || field == constants.last_name.

Upvotes: 0

Views: 175

Answers (2)

SibiCoder
SibiCoder

Reputation: 1496

You can do that with a macro. Press qaq to empty a register.

Go to line 1 by pressing :1

Press qa to start recording in a register.

Then, search text like /"\S\+". It will highlight the text.

Then, type xiconstants. and then press ESC, then f", then x.

Type @a to replay the register recursively. Stop recording by pressing q.

Hereafter, you can press @a once and it will replace everywhere recursively until all such words are changed.

Upvotes: 1

dNitro
dNitro

Reputation: 5345

Using search and replace, just run the following command:

%s/\("\)\([^"]\{-}\)\1/constants.\2/g

part by part:

% - In all lines
s - substitute
\("\)\([^"]\{-}\)\1 - part1 (find any string that is surronded by double-quotes)
constants.\2 - by part2 (add constants. to second cached group in regex)
g - globally

Upvotes: 1

Related Questions