Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

character case conversion Uppercase to Lower and vice versa

Tags:

shell

unix

I was trying to convert the lowercase characters to uppercase. I came across various alternatives like one listing at the StackOverflow question. However, What i saw that these are just printed. I want to save it to another variable which i can use later. Can anyone tell how i can achieve this?

like image 694
Abhinav Avatar asked Jan 25 '12 10:01

Abhinav


2 Answers

I know this is an oldish post but I made this answer for another site so I thought I'd post it up here:

here comes a programmers answer....

UPPER -> lower: use python:

b=`echo "print '$a'.lower()" | python`

Or Ruby:

b=`echo "print '$a'.downcase" | ruby`

Or Perl (probably my favorite):

b=`perl -e "print lc('$a');"`

Or PHP:

b=`php -r "print strtolower('$a');"`

Or Awk:

b=`echo "$a" | awk '{ print tolower($1) }'`

Or Sed:

b=`echo "$a" | sed 's/./\L&/g'`

Or Bash 4:

b=${a,,}

Or NodeJS if you have it:

b=`echo "console.log('$a'.toLowerCase());" | node`

You could also use dd (but I wouldn't!):

b=`echo "$a" | dd  conv=lcase 2> /dev/null`

lower -> UPPER:

use python:

b=`echo "print '$a'.upeer()" | python`

Or Ruby:

b=`echo "print '$a'.upcase" | ruby`

Or Perl (probably my favorite):

b=`perl -e "print uc('$a');"`

Or PHP:

b=`php -r "print strtoupper('$a');"`

Or Awk:

b=`echo "$a" | awk '{ print toupper($1) }'`

Or Sed:

b=`echo "$a" | sed 's/./\U&/g'`

Or Bash 4:

b=${a^^}

Or NodeJS if you have it:

b=`echo "console.log('$a'.toUpperCase());" | node`

You could also use dd (but I wouldn't!):

b=`echo "$a" | dd  conv=ucase 2> /dev/null`

Also when you say 'shell' I'm assuming you mean bash but if you can use zsh it's as easy as

b=$a:l

for lower case and

b=$a:u

for upper case.

like image 116
nettux Avatar answered Sep 30 '22 06:09

nettux


Your input is $a. The new variable is $b.
(borrowed from here written by @ghostdog74)

using tr:

b=$( tr '[A-Z]' '[a-z]' <<< $a)

if you use tcsh, then use echo instead of <<<:

set b=`echo "$a" | tr '[A-Z]' '[a-z]'`
like image 24
oHo Avatar answered Sep 30 '22 07:09

oHo