Is there a command to find and replace all instances of a number in a file with 0 (including decimal numbers like 1.7
)?
1 Answer
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.
-
9