Substring in sh

Substring in sh

Post by Mats Larss » Tue, 16 Nov 1999 04:00:00



Only one problem with this. If the string is shorter than 3 characters this
statement returns nothing. Maybe You want the the whole string to be returned
in these cases.




>> [ This is a repost of an article that didn't make it beyond the local
>>   network.  Sorry if the topic is a bit out of date. ]


>> >>how can i extract the 3 last characters of a string ?

>> >If you're using ksh, bash, POSIX shell etc, try using:

>> >typeset -R3 fred=${jim}

>> POSIX shells are not required to support "typeset".  Those that do
>> are probably just ksh in disguise.

>How about this?
>expr $string : '.*\(...\)'

 
 
 

Substring in sh

Post by Ken Pizzi » Wed, 17 Nov 1999 04:00:00



Quote:>>> >>how can i extract the 3 last characters of a string ?
>>> >If you're using ksh, bash, POSIX shell etc, try using:
>>> >typeset -R3 fred=${jim}
>>> POSIX shells are not required to support "typeset".  Those that do
>>> are probably just ksh in disguise.
>>How about this?
>>expr $string : '.*\(...\)'
>Only one problem with this. If the string is shorter than 3 characters this
>statement returns nothing. Maybe You want the the whole string to be returned
>in these cases.

This should be highly portable:
  case $string in
    ???*) expr "$string" : '.*\(...\)' ;;
    *) cat <<END ;;
$string
END
  esac

                --Ken Pizzini