Search code examples
regexlinuxvimreplace

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:

%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. romainl's answer shows that way.)