Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim: substitute characters from backreference

I want to do the following subtitutions in vim: I have a string (with spaces eventually) and a number at the end of the line. I want to create a C #define with that string in uppercase + a prefix + underscores, the number (in hex) and finally the original string as a comment.

For example, from:

hw version 0

to:

#define MY_HW_VERSION (0x00) // hw version

So far, I wrote the following regex:

s/^\(.*\) \(\d\+\)$/#define MY_\U\1\E (0x0\2)\/\/ \1/

which gives

#define MY_HW VERSION (0x00) // hw version
  • uppercase: OK (use \U to start uppercasing and \E to end it)
  • prefix: OK
  • number: OK (hex might be an issue, but that is not the purpose of my question)
  • comment: OK (reuse back-reference \1)

But can you see the space left? MY_HW VERSION instead of MY_HW_VERSION...

So I'd like to make a substitution in the back-reference \1 like \1:s/\s/_/g. Is it possible at all? How to do it?

Thanks!

like image 294
CJlano Avatar asked Sep 18 '26 05:09

CJlano


1 Answers

this would be the one-line :s cmd, works for your example: (I break it into multi-lines, just for better reading)

s@\v(.*) (\d+)@
\='#define MY_'
.toupper(substitute(submatch(1),' ','_','g'))
.' (0x0'.submatch(2).') //'.submatch(1)@
like image 152
Kent Avatar answered Sep 20 '26 19:09

Kent