Let say i have a variable name
holding some string value
To fetch last n characters, in bash we write :
$ echo "${name: -n}"
what is the equivalent way in ksh
, i have seen sed
and awk
methods but what i am looking for is one line or piping solution similar to bash
to extract last characters
These are errors and efforts so far :
AB12 $ name="123456"
AB12 $ echo ${name:(-3)}
ksh: ${name:(-3)}: bad substitution
AB12 $ echo${name:0:-3}
ksh: echo${name:0:-3}: bad substitution
AB12 $ print ${name%?}
12345
AB12 $ echo "some string" | tail -c -1
tail: cannot open input
AB12 $ echo -n "my string discard"| tail -c -1
tail: cannot open input
AB12 $ echo "foo"| cut -c 1-2
fo
AB12 $ echo "foo"| cut -c -2
fo
AB12 $ echo $name
123456
AB12 $ echo "${name: -3}"
ksh: "${name: -3}": bad substitution
I am on Solaris currently - if this helps!
You can use this, say n=2 (we will use 2 question marks in the nested expansion):
$ var="this is my var"
$ echo "${var#${var%??}}"
ar
Explanation
It is a nested expansion.
The expansion ${var%%??}
is embedded in the expansion ${var# }
.
The ${var#string}
expansion will cut off anything from the beginning of the variable which matches 'string'. So we are saying in this instance, removing anything from the beginning of the variable which matches ${var%%??}
.
On its own, ${var%%??}
matches "this is my v" for the variable in the example, as the%%
expansion matches the longest possible match at the end of the variable. In this case, two regexp ?'s.
Your cut is looking good, just get the correct offset.
#!/bin/ksh
var="This is a string"
n=2
(( offset = ${#var} - $n + 1 ))
echo ${var} | cut -c ${offset}-
or as a oneliner
echo ${var} | cut -c $(expr ${#var} - $n + 1 )-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With