James Raitsev
James Raitsev

Reputation: 96391

Search and replace regex in VI, clarification needed

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

Upvotes: 3

Views: 1013

Answers (2)

William Pursell
William Pursell

Reputation: 212248

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

Upvotes: 3

John Dewey
John Dewey

Reputation: 7093

In Perl,

my $t = "Some text
1 101 12
1 102 13
2 200 2
2 202 4
2 201 7
3 300 0
3 301 7
Some other text";

foreach (split /^/, $t) {
  $_ =~ s/^([1-3])/# $1/;
  print $_;
}

Result:

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

Upvotes: 0

Related Questions