Line numbers in VIM's search & replace

Often, I have to assign a list of Selenium parameters $p1 through $pN to a list of more meaningful names. With VIM, this is easily done. First, place the meaningful names in the editor, one name per line:

name
street
housenumber
city

Then type the command :%s/.*/#set $& = $pXXX and hit enter. This is the result:

#set $name = $pXXX
#set $street = $pXXX
#set $housenumber = $pXXX
#set $city = $pXXX`

Now all that’s left is to change the XXX to the appropriate number. Type :%s/XXX/\=line(".") and hit enter to get this:

#set $name = $p1
#set $street = $p2
#set $housenumber = $p3
#set $city = $p4

Of course, this is all rather trivial. However, with longer list and slightly more complex regular expressions, this is a very powerful technique. Think about 30 files with 20 #set commands per file, and you have to insert one more at the top and rename the rest. With VIM, that’s a piece of cake.

By the way - both commands could have been combined into one. However, that would make the commands more complex and hard to understand. For the curious, the command is :%s/.*/\="#set $" . submatch(0) . " = $p" . line(".")

dr. Sybren A. Stüvel
dr. Sybren A. Stüvel
Open Source software developer, photographer, drummer, and electronics tinkerer

Related