Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace, reusing token, in Vim

Tags:

regex

replace

vim

I'm having trouble crafting the appropriate find/replace regex to use in Vim.

Here's some SQL:

select avg(field_name1), avg(field_name2), avg(field_name3) from a_table

Oops, I forgot to alias the results:

select avg(field_name1) field_name1,
avg(field_name2) field_name2, avg(field_name3) field_name3 from a_table

So, in Vim, I'm sure there's a handy find and replace to match an arbitrary [a-z]\+_[a-z]\+ inside parenthesis, but I can't figure out how to put that token after the entire match

like image 466
justin cress Avatar asked Sep 05 '12 17:09

justin cress


2 Answers

Try the following:

:s/(\(.*\))/(\1) \1/g
like image 124
rks Avatar answered Oct 24 '22 19:10

rks


Group the text that you want to use in the substitution/replacement with surrounding \(\), and refer to these back-references in the substitution using \1, \2, etc.

Using [:alnum:] to match alphanumeric characters:

:s/(\([[:alnum:]]\+_[[:alnum:]]\+\))/(\1) \1/g

To apply either regex to the entire file, use:

:%s/(\([[:alnum:]]\+_[[:alnum:]]\+\))/(\1) \1/g

See also :help \1 for more details about using back-references.

like image 35
pb2q Avatar answered Oct 24 '22 17:10

pb2q