Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use regex in vim to toggle case for all characters in a file

I have a file which has the following text

Lorem IpSuM is SIMPLY duMMy TeXt of the PrINtinG and typesetting industry.
Lorem Ipsum has been the industry's stanDaRd dummy text ever since the 1500s,
whEn an unknown printer took a galley of type and sCrAMBled it to MakE a type specimen BoOk.

After toggling the case of all the characters the text file should look like:

lOREM iPsUm IS simply DUmmY tExT OF THE pRinTINg AND TYPESETTING INDUSTRY.
lOREM iPSUM HAS BEEN THE INDUSTRY'S STANdArD DUMMY TEXT EVER SINCE THE 1500S,
WHeN AN UNKNOWN PRINTER TOOK A GALLEY OF TYPE AND ScRambLED IT TO mAKe A TYPE SPECIMEN bOok.

I am using the following regex pattern:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

%s/\<\([A-Z\s\]+\)\>/\L&/

But vi editor is throwing an error:

E486: Pattern not found: \<\([A-Z\s\]+\)\>/\L&/

What is the correct pattern for toggling case of all characters in a file at once using regex in vim?

>Solution :

Why going for regex and :s, if you can do ggShift+vG~?

If you have to do it in a script, you can use :normal:

:normal ggVG~

Well, if you really want to go for :s, you can do this

%s/\a/\=submatch(0) >= 'a' && submatch(0) <= 'z' ? toupper(submatch(0)) : tolower(submatch(0))/g

(I suspect there’s a way to write submatch(0) >= 'a' && submatch(0) <= 'z' more concisely, but I don’t know of it, or it simply doesn’t come to my mind.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading