The linux shell has provided us with many hidden gems. Some of things are string manipulation without using external commands like SED/AWK. In this post we will see how to convert a string from lower case to upper and upper case to lower by using string manipulation techniques and tr command.
String manipulation for lower case to upper case:
Note: Below examples will work in bash v4 and above versions.
Example1: Convert an entire string from lower to upper
Example:
VAR1=surendrakumar
VAR2=${VAR1^^}
echo $VAR2
SURENDRAKUMAR
Example2: Convert only first character to upper case.
Example
VAR1=surendrakumar
VAR2=${VAR1^}
echo $VAR2
Surendrakumar
Example3: Suppose you just want to convert a specific characters like a,d,e then use below code.
VAR1=surendrakumar
VAR2=${VAR1^^[ade]}
echo $VAR2
surEnDrAkumAr
Example4: Convert an entire string from upper to lower
Example:
VAR1=SURENDRAKUMAR
VAR2=${VAR1,,}
echo $VAR2
surendrakumar
Example5: Convert only first character to lower case.
Example
VAR1=SURENDRAKUMAR
VAR2=${VAR1^}
echo $VAR2
sURENDRAKUMAR
Example6: Suppose you just want to convert a specific characters like A,D,E then use below code.
VAR1=SURENDRAKUMAR
VAR2=${VAR1^^[ADE]}
echo $VAR2
SUReNdRaKUMaR
Example7:How about using tr command?
lower case to upper case
VAR1=surendrakumar
echo $VAR1 | tr '[a-z]’ ‘[A-Z]'
Output:
SURENDRAKUMAR
Upper case to lower case
VAR1=SURENDRAKUMAR
echo $VAR1 | tr '[A-Z]’ ‘[a-z]'
Output:
surendrakumar
Hope this helps some one not use sed and awk for just case convertions.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018