Operating System - HP-UX
1756432 Members
2869 Online
108847 Solutions
New Discussion юеВ

Re: how to capture last 2 digits/chars of variable

 
SOLVED
Go to solution
Rodney Hills
Honored Contributor

Re: how to capture last 2 digits/chars of variable

Here's one more that uses only shell internal commands.

$ x="abcdefg"
$ typeset -R2 y=$x
$ echo $y
fg

"typeset" is an internal command to the shell, so no external processes are run.

HTH

-- Rod Hills
There be dragons...
curt larson_1
Honored Contributor

Re: how to capture last 2 digits/chars of variable

Could you explain the last assignment...what does the #$x do?

from procura's cut and paste,

x=${var%??}

This removes the smallest suffix from the variable that matches the pattern. The pattern is this case is ??. ? matches any character. So, this removes the last two characters from var.

last2char=${var#$x}

this removes the smallest prefix pattern from the variable. From above, $x is everything but the last two characters. So, this removes everything from the front of var except the last two characters. Which leaves you with just the last two characters that your looking to get.
Cem Tugrul
Esteemed Contributor

Re: how to capture last 2 digits/chars of variable

Let's try to get "anip" from the string "manipulate"

#!/bin/sh
s="manipulate"
s1=`expr substr $s 2 4`
echo $s1
-----------------------
echo "manipulate" | cut -b 2-5
------------------------
s=manipulate
echo $s | awk '{print substr($0,2,4)}'
-------------------------

Good Luck,
Our greatest duty in this life is to help others. And please, if you can't
Jdamian
Respected Contributor

Re: how to capture last 2 digits/chars of variable

I prefer Rodney Hill's solution:

typeset -R2