Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching last n characters of string in ksh

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!

like image 653
NoobEditor Avatar asked Jan 11 '23 07:01

NoobEditor


2 Answers

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.

like image 116
Ell Avatar answered Jan 18 '23 22:01

Ell


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 )-
like image 22
Walter A Avatar answered Jan 18 '23 22:01

Walter A