Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace regex in VI, clarification needed

Tags:

regex

vi

Given the following, i'd like to comment lines starting with 1 or 2 or 3

Some text
1 101 12
1 102 13
2 200 2
// Some comments inside
2 202 4
2 201 7
3 300 0
3 301 7
Some other text

The following regex (seems to) look(s) right, and yet it does not work ..

%s/^([123])(.+)/#\1\2/g

The same regex matches when used by egrep

egrep '^([123])(.+)' file_name

Please help me understand why this search and replace is failing in VI

like image 290
James Raitsev Avatar asked Jan 20 '26 12:01

James Raitsev


1 Answers

You need to escape the characters: ()+. So you could do %s/^\([123]\)\(.\+\)/#\1\2/g, but it seems easier to do: :g/^[123]/s/^/#

Note that vi does have various options for changing the meaning of symbols in patterns (help magic). In particular, you could use 'very magic' and do: :%s/\v^([123].+)/#\1/g (note that the g flag is completely redundant here!)

like image 99
William Pursell Avatar answered Jan 22 '26 06:01

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!