Using an expression in substitute command
From Vim Tips Wiki
Tip 755 Previous Tip • Next Tip
Created: June 26, 2004 Complexity: intermediate Author: Raj Kiran Grandhi Minimum version: 5.7 Karma: 66/23 Imported from: Tip#755
You can use an expression as the replacement string in the substitute command (:s). When the replacement string starts with "\=" it is evaluated as an expression. This opens whole new avenue of interesting possiblities. Here are a few examples:
1. Number all the lines in a file:
:%s/^/\=line('.').'^I'/
2. Number a range of lines (from line 10 to line 20):
:10,20s/^/\=line('.').'^I'/
3. Number a range of lines sequentially starting from 1:
:let counter=0|10,20g//let counter=counter+1|s/^/\=counter.'^I'
4. To number all the paragraphs in range starting from 1 (assuming the paragraphs are separated by one or more blank lines):
:let counter=0|1,20g/^$\n^\s*[^\s]/let counter=counter+1|+1s/^/\=counter.'^I'
Note: The above command does not work for the first paragraph in the file if there is no blank line above it.
[edit] References
[edit] Comments
You can also substitute inside substitute!
:%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/
.* is the submatch(0)
The substitute expression will replace any "/" by "_", for example changing line:
sub1/sub2/file1.html
to
cp sub1/sub2/file1.html sub1_sub2_file1.html
See VimTip305 for a few more.
To do incremented columns, check out VimTip150 : incremented, decremented, daynames, dates, etc.
