Now I am absolutely certain I will hear a voice from far above (or maybe a bit closer to New York) booming out at me “THIS CAN BE DONE WITH REGULAR EXPRESSIONS!”
I’m pretty certain of that. I don’t claim to have mastered Regular Expressions. But I had a simple need today. Converting cases of words in Powershell.
In my case I had a list of data that was in ALL UPPERCASE and since that feels a bit like shouting I wanted to do something with it.
In Powershell we have many built in methods to manipulate string data. There are three I’m going to play with today, toupper, tolower and substring.
For example if I have this string….
$Sonnet=“There once was a Canadian Nerd, WHO saNG like an OFFKEY Bird…”
I can switch all of the characters to lowercase by using this method
Which will give us the following output
there once was a canadian nerd, who sang like an offkey bird…
If I would like to make it look like I’m shouting so everybody in Texas can hear me I can switch it all to uppercase
Which (Cover your ears as I’ll now be shouting) looks like this.
THERE ONCE WAS A CANADIAN NERD, WHO SANG LIKE AN OFFKEY BIRD…
Sorry that was a bit loud. But you can see switching cases is quite trivial. But here’s the fun. What if you have to ensure a word is just Capitalized?
For that bit of trickery we can leverage Powershell and the magic substring command.
First let’s take a look at this loud and abusive word.
If we’d to present our good friend with JUST the name capitalized, we can grab the first character with a substring, pop it into uppercase like so
The audience “Oooohs” and “Ahhhs” in the background. Without knowing the length of the word, we can use substring to grab all characters from the second character to the end and switch to lowercase
….More gasping from the audience…
And so with a wave of my hand and the magic words “Snoopy Dance”
Now our good friend will appear less frightening to the general public. Of course I’m having a bit of fun here but I had a situation where I had a list of full names that were in all uppercase. Yes it was my own fault, a bad accident between an auto user generator for a Demo environment and an overly caffeinated “toupper()” method (or a broken CAPSlock key, the details are fuzzy). So in my case I had a perfectly good list of names like
Perfectly good, except they were all SHOUTING!
What to do? Just grab each name, split ‘em and use my new evil powers before creating their names in my demo system
Ok, maybe it’s partially useful and the gods of Regex will probably smite me down, but I’m an ITPro.
Have mercy on me.
The Energized Tech
The Power of Shell is in YOU