Extract the last character of a string

How can I extract the last character of a string (withou knowing how many characters are in that string ! )

[muru:~]cat lastchar
word=$1
num=`echo $word | wc -c `
let num-=1
last=`echo $1 | cut -c$num`
echo $last

assumptin: the string that comes after scriptname (its lastchar here) is the string for which u need the last charactor for. Hope this is helpful.

It could be done in a simple way also, not sure how for now!

$ echo "some string" | sed -e "s/^.*\(.\)$/\1/"
g
$

1 Like

You can use the ksh builtin typeset feature.

[/tmp]$ cat try.ksh
#! /bin/ksh

typeset -R1 right

STR="some string"
right=$STR
echo $STR
echo $right

[/tmp]$ ./try.ksh
some string
g
[/tmp]$ 

I guess this is a common question and most people suggest the use of sed or awk. so here's my contribution:
Two commands which typically are forgotten is head and tail which allow also to process standard input if you ommit a file.
For instance, if you want a string without the last character you can do:
echo -n "my string discard" | head -c -1
the result is "my string discar"

if you want the last character of a string use tail instead:
echo -n "my string discard"| tail -c -1
the resut is "d"

notes:
-the use of -n in echo avoids a newline in the output
-in the -c option the value can be positive or negative, depending how you want to cut the string.

Carlos.

The following is assuming Korn Shell and might not work if you shell is very different from the ksh.

To chop off the last character of a string use ${var%%?}. Example:

hugo="abcd"
print - ${hugo%%?}       # will yield "abc"

To display the last character only (without using any external tools) you can nest the above construction:

print - "${hugo##${hugo%%?}}"     # will yield "d"

I hope this helps.

bakunin

#/bin/ksh93

hugo="abcd"
$ print ${hugo}
abcd
$ print ${hugo: -1}
d
$

The above syntax is supported by bash too.

Another one:

zsh-4.3.4% hugo=abcd;print $hugo[-1]
d
# a=fgdgfd
# echo `expr "$a" : '.*\(.\)'`
d