How to convert lower case variable into upper case?

Stuart Poulin stuart at amc-gw.amc.com
Sat Jan 26 08:31:03 AEST 1991


#!/bin/sh

# Here's a couple of fun ways to translate the last char to upper
# case.

# These work for any last character of a-z.

# First, the little used expr. 

Port=i1o
case $Port in
    i1[a-z]) tmp_port=`expr "$Port" : '\(.*\).'`
             Port=$tmp_port`expr "$Port" : '.*\(.\)' | tr 'a-z' 'A-Z' `
        ;;
esac
echo $Port

# Or using associative arrays in awk. (this even works in old awk).
# I seem to do a lot of char translations this way.
#( I used a sh function to simplify the case statement.)

ToUpperLastChar() {
echo $*|
awk  '
BEGIN {
    # build an associate array to do the translation
    split("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",\
                        low_alpha,",") 

    split("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",\
                        high_alpha,",")

    for ( i = 1 ; i < 26 ; i++){
        trans[low_alpha[i]] = high_alpha[i]
        trans[high_alpha[i]] = low_alpha[i]
    }       
}


{ 
    StrLen=length($0)
    print substr($0,1,StrLen - 1) trans[substr($0,StrLen)]
}'

}

Port=i1o
case $Port in
     i1[a-z]) Port=`ToUpperLastChar "$Port`
            ;;
esac
echo $Port



More information about the Comp.unix.shell mailing list