Reputation: 1075
I have a number 2014061200
and I am trying to extract the one's digit of this number (0
) and set it to a variable $STR
, so that $STR
would equal 0
, because that is in the one's place of the above number.
I made a shell script showing the following:
$NUM=2014061200
$STR= $NUM | tail -c 2
echo $STR
However when I do this I get a blank for $STR
instead of the expected result of 0. I mean when I type
echo $NUM | tail -c 2
, I do get the output of 0, but how do I get this into a variable?
Thanks
Upvotes: 1
Views: 3268
Reputation: 10314
Here's another variation using parameter expansion where ${#num}-1
is the length of the string less 1 and ${num:position:length}
is a substring expression:
${num:(${#num}-1):1}
Upvotes: 1
Reputation: 241808
Use parameter expansion:
num=2014061200
last=${num: -1}
-1
tells bash to extract one character from the right.
Upvotes: 5