searchreplacevimwildcardvi

Find and Replace using wildcard in VIM or VI


I have a file with numbered host names. I want to change the name while preserving the numbers.

CHANGE THIS:

server1.domain.com
server2.domain.com
server3.domain.com
server4.domain.com
server1.otherdomain.com
server2.otherdomain.com

TO THIS:

host1.domain.com
host2.domain.com
host3.domain.com
host4.domain.com
server1.otherdomain.com
server2.otherdomain.com

I have tried this but it does not work :%s/server*.domain.com/host*.domain.com/g


Solution

  • You could use a capture group, and make the match a bit more specific by matching the numbers and escaping the dot.

    Then in the replacement use the capture group denoted as \1

    :%s/server\([0-9]\+\.domain\.com\)/host\1/g
    

    Result:

    host1.domain.com
    host2.domain.com
    host3.domain.com
    host4.domain.com
    server1.otherdomain.com
    server2.otherdomain.com