There is a nice answer to get last char of string
str='abcd/'
echo "${str: -1}"
how to get second to last i.e. return 'd' instead of '/'
As you already seem to know, negative positions are relative to the end of the string, so -1 starts at the last character, -2 would start at the penultimate character, and so forth.
However, the form you use is the simplified form of taking the substring, it takes all characters from the specified position to the end of the string.
You can also supply an explicit length to get a limited number of characters starting at the position so, to get the second last character, all you need is:
${str: -2:1}
The relevant bits of the bash documentation are:
${parameter:offset}
${parameter:offset:length}Substring Expansion. Expands to up to
lengthcharacters of the value of parameter starting at the character specified byoffset.If
lengthis omitted, expands to the substring of the value of parameter starting at the character specified byoffsetand extending to the end of the value.
str='abcd/'
echo "${str: -2:-1}"
returns 'd'
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