convert strings from mixed to upper case in windows batch scripting
Is there a way to convert strings from mixed to upper case in windows batch scripting?
I am writing a batch file to create certain objects and grant user groups access to them. That is, I should issue commands like
cas caslibs create path --name CAS_HRCOCKPIT --path /sas/data/projects/HRCOCKPIT /
cas caslibs add-control --name CAS_HRCOCKPIT --group GSSASELA-DEVHRCockpitUsers --grant read
cas caslibs add-control --name CAS_HRCOCKPIT --group GSSASELA-DEVHRCockpitAdmins --grant modify
The objects should be in upper case, but the user groups are not. How do I converts a string like Cockpit
into HRCOCKPIT
?
I’m not sure I understand your question 100%.
You seem to be asking how to convert (the value of) a variable
in a Windows batch file from mixed to all upper case.
If so, the Super User question How to make uppercase all files and folder
on a directory?, by seçkin bilgiç, contains an answer.
Assuming that your variable is called obj
(i.e., you have done set obj=Cockpit
), do
setlocal enableDelayedExpansion
︙
for %%A in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
set "obj=!obj:%%A=%%A!"
)
This uses the %variable:old=new%
syntax
for doing a substitution in a variable value.
For example, if we do set animal=cow
, then %animal:ow=at%
yields cat
.
A useful feature of this is that the match for the old string
is case-insensitive, but the replacement is case-preserving;
so %animal:OW=AT%
yields cAT
.
Similarly, if obj=Cockpit
, then %obj:T=T%
yields CockpiT
,
and so we can use this to replace a letter
with the upper case version of itself.
We loop through the alphabet, getting the effect of
set "obj=%obj:A=A%"
set "obj=%obj:B=B%"
set "obj=%obj:C=C%"
︙
without having to do all 26 statements.
But variables behave strangely in loops in batch files.
That’s why we have setlocal enableDelayedExpansion
,
and why we use !...!
rather than %...%
in the assignment in the loop.