Operating System - HP-UX
1823114 Members
3184 Online
109646 Solutions
New Discussion юеВ

How to extract last character in a variable

 
SOLVED
Go to solution
Tom Krocak_1
Advisor

How to extract last character in a variable

I have a variable "V1" that contains a number of numeric characters and I would like to set "V2" to be the last character in V1. How can I do this in ksh script. (Example: V1=25386, would like to get V2=6)
5 REPLIES 5
Brian Bergstrand
Honored Contributor
Solution

Re: How to extract last character in a variable

POS=`echo $V1 | wc -m`
#acct for newline
let POS=$POS-1
V2=`echo $V1 | cut -c $POS`

Quick and dirty, but it works.
HTH.
John Poff
Honored Contributor

Re: How to extract last character in a variable

Hi,

Here is one way to get it using awk:

V1=25386
V2=$(echo $V1 | awk '{print substr($1, length($1), 1)}'

The local wizards will probably post some more elegant methods for you, but this is how one poor sysadmin would try it.

JP
Tom Krocak_1
Advisor

Re: How to extract last character in a variable

Thanks - I like both answers.
curt larson_1
Honored Contributor

Re: How to extract last character in a variable

cant remember which will work for your case,
but -L is left justified and -R is right justified. (not even sure if this is supported on hp's old 88 version of the korn shell).

typeset -L 1 v2=$v1
or
typeset -R 1 v2=$v1

if it is support one of these will work
Hai Nguyen_1
Honored Contributor

Re: How to extract last character in a variable

Hi,

You can employ the modulo technique in math as follows:

V2=`echo $V1%10 | bc`
echo $V2

Hope this helps.

Hai