6

Is there a command to find and replace all instances of a number in a file with 0 (including decimal numbers like 1.7)?

9

Based on the help file, and the Vim Wikia page on Search and replace

:%s/[0-9]\+\.[0-9]\+\|[0-9]\+/0/g

:%s - start a command with the range of the entire file, %, to substitute, the following patterns:

[0-9]\+\.[0-9]\+

This must come first, it's the pattern that covers decimals like 1.7. In addition it will only match a number followed by a period, without replacing the period. [0-9] is the collection for any digit. The \ is required to escape the special characters, +, which means match one or more occurrences. The . needs to be escaped, so that it doesn't take on it's normal meaning of match any character.

| means or, as in match the first pattern or the second, and must be escaped.

Then the pattern for any digit, one or more times, [0-9]\+ again.

/0/g

Finally, replace every occurrence of the pattern on the line with 0.

For example,

123
1.7
8
99
2.

becomes

0
0
0
0
0.
  • 8
    can simplify to :%s/\v\d+(\.\d+)?/0/g – Sundeep Nov 24 '16 at 2:27

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.