MalavShelat
MalavShelat

Reputation: 23

Search and replace by using the searched pattern using wild card in vi

I have below lines in a file:

HELLO(qwqwq)
My name ()
Your name ()
HELLO(dsdasd)
HELLO(sdsdsdasdasdasf)

I want it to be replaced as follows:

qwqwq:
My name ()
Your name ()
dsdasd:
sdsdsdasdasdasf:

Here I have a pattern HELLO(.*) that can be used in a search and replace command but how to do it in vim ?

Upvotes: 1

Views: 623

Answers (2)

SergioAraujo
SergioAraujo

Reputation: 11800

First, make a search (I opted to not use very magic mode) because either way, I have to use escape "\" using very magic or not, it only changes the place I have to use it.

/HELLO(\([^)]*\))
( ..................... regular parenthesis 
\( .................... start group 1
[^)]* ................. denies everything until \) closing group 1
\)  ................... close group 1
) ..................... regular parenthesis

Once you have tested your search pattern you can use it in your search, here I am using another separator instead slash. Omitting the search pattern will make vim use the previous search as the pattern.

%s,,\1,g

I like this approach because is safer, before making any change we can test with a search

Upvotes: 0

Kent
Kent

Reputation: 195049

This line will help you for the given example:

%s/\vHELLO\(([^)]*).*/\1:/

With :g and normal command is also easy:

:g/HELLO/norm! %yi(VpA:

Upvotes: 3

Related Questions