Shell: Extract the last character from a string

April 12, 2012 · Posted in Scripting, Shell 

With the command ‘cut’ it is easy to extract the first, second, third or any character of a string.

$ echo qwerty | cut -c 1
q
$ echo qwerty | cut -c 2
w
$ echo qwerty | cut -c 3
e

But this is not useful if you want to extract the last character of the string without know the lenght of it. To do it the first thing is know the position of this character. You can do this with the ‘#’ modificator to get the size.


$ word="qwerty"
$ echo ${#word}
6

Now you can use this tip to extract the last character.


$ echo $word | cut -c ${#word}
y

 

Comments

Comments are closed.