Welcome to the news archive. Here you'll find all the news items, ordered by date. You can use the links below to read other news items, or go back to the archive overview.
2007-03-26 16:30 - 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(".")
Comments
Looks nice. However, can you bind all those actions to a single key command so that you only have to think about it once?
by Sybren Stüvel - 3 years, 4 months ago.
There's a typo in your example - the line
:%s/XXX/\=line(".")
should read:
:%s/XXX/=line(".")
otherwise this substitution doesn't work.
by - 3 years ago.
Hmmm... my post got mangled on submission, so my correction is incorrect too. Basically you've got two slashes before the equals sign and there should only be one.
by - 3 years ago.
Thanks Paul, I've updated the article.
by Sybren Stüvel - 3 years ago.
Cool,
A great article to demonstrate line numbers,
Thanks
by custom software - 9 months, 1 week ago.
Post a comment
All fields are required, except when otherwise noted. You can use a limited subset of Restructured Text to markup the comment.
It might take up to five minutes for your comment to show up, due to caching of the pages.
Great!
However, I prefer to use a user friendly tool like pspad.
Yes, it can do the above:
type the variable names
add line numbers (alt+i)
search ^(\d*) (.*)
and replace with #set \$$2 = \$$1
Pspad also inserts a character d when you type one ;-)
by Bas Vermeulen - 3 years, 4 months ago.