0

I would like to replace a string with regular expression that appears in multiple lines with the character "x":

The problem is to replace words with the x in front that has an integer after the x, such as in a file that contains:

x44name
xjanname
x50name

For example:

:1,2s/x[0-9]name/num/g

Would I need to use sed or some other command to search and replace the word?

The following error occurs:

E486: Pattern not found: x[0-9]name
  • 1
    your substitution will replace one (1) digit, your sample line have two (2). your substitution is ok thou, try %s/x[0-9][0-9]name/num/ (by the way no need for g if you have only one pattern per line). – Archemar May 28 '15 at 13:59
1

If you can have any number of digits (including 0) you should do

:%s/x[0-9]*name/num/g

if it's always two

:%s/x[0-9][0-9]name/num/g

of course you can also use \d instead of [0-9]

:%s/x\d*name/num/g
  • %s means search the whole file
  • s means just search the current line

  • g means all matches in a given line

  • no g means only the first match per line is replaced
  • So the asterisk symbol * is essential for finding all numbers from the list? – Juan Davila May 28 '15 at 18:18
  • 1
    It matches 0 or more times. You could also instead use a + symbol. That will match 1 or more times. – jhenn May 28 '15 at 18:50
0

If I understand you correctly, and "num" it is number that next in order after "x", catch this out:

:%s/x\([0-9]\)/\1/g

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.