Reputation: 825
I am a beginner at Vim and I've been reading about substitution but I haven't found an answer to this question.
Let's say I have some numbers in a file like so:
1
2
3
And I want to get:
(1)
(2)
(3)
I think the command should resemble something like :s:\d\+:.......
. Also, what's the difference between :s/foo/bar
and :s:foo:bar
?
Thanks
Upvotes: 2
Views: 546
Reputation: 196789
Here is an alternative, slightly less verbose, solution:
:%s/^\d\+/(&)
Explanation:
^ anchors the pattern to the beginning of the line
\d is the atom that covers 0123456789
\+ matches one or more of the preceding item
& is a shorthand for \0, the whole match
Upvotes: 12
Reputation: 6258
You can do what you want with:
:%s/\([0-9]\)/(\1)/
%s
means global search and replace, that is do the search/replace for every line in the file. the \( \)
defines a group, which in turn is referenced by \1
. So the above search and replace, finds all lines with a single digit ([0-9]
), and replaces it with the matched digit surrounded by parentheses.
Upvotes: 1
Reputation: 771
Let me address those in reverse.
First: there's no difference between :s/foo/bar
and :s:foo:bar
; whatever delimiter you use after the s
, vim will expect you to use from then on. This can be nice if you have a substitution involving lots of slashes, for instance.
For the first: to do this to the first number on the current line (assuming no commas, decimal places, etc), you could do
:s:\(\d\+\):(\1)
The \(...\)
doesn't change what is matched - rather, it tells vim to remember whatever matched what is inside, and store it. The first \(...\)
is stored in \1
, the second in \2
, etc. So, when you do the replacement, you can reference \1
to get the number back.
If you want to change ALL numbers on the current line, change it to
:s:\(\d\+\):(\1):g
If you want to change ALL numbers on ALL lines, change it to
:%s:\(\d\+\):(\1):g
Upvotes: 8