Extracting substring from variable

Hi All,

I'm facing issue wherein I have 2 character string like 'CR' and 'DR' and I want to extract just 1st character but am unable to do it. I tried below options but they are returning me 2nd character only,

var="CR"
echo ${var:1}

returns just "R"

echo ${var:0}

returns "CR"

expr substr $var 1 1

doesn't work at my end it.

Any suggestions please.

Thanks,
Arvind.

${var:0:1}

What shell are you working in?

If it's ksh (and possibly bash too) you can do this sort of thing:-

echo ${var%?}

It looks shocking, but it is slicing the variable up a little. It is called variable substitution and you should be able to get a fuller explanation if you search for that. It would probably not be best if I try to re-write existing documentation.

I hope that this helps,
Robin

The one below should work irrespective of shell version...

export var="DR"
echo ${var%"${var#[A-Z]}"}
D
typeset -L1 var

Thanks alot to all, all the solution mentioned worked.