Technology
 

Using an expression in substitute command

From Vim Tips Wiki

(Redirected from VimTip755)

Tip 755 Previous Next created June 26, 2004 · complexity intermediate · author Raj Kiran Grandhi · version 5.7


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:

  • Number all the lines in a file:
:%s/^/\=line('.').'^I'/
  • Number a range of lines (from line 10 to line 20):
:10,20s/^/\=line('.').'^I'/
  • Number a range of lines sequentially starting from 1:
:let counter=0|10,20g//let counter=counter+1|s/^/\=counter.'^I'
  • 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.