I have written the following lines to get the last character of a string:
str=$1 i=$((${#str}-1)) echo ${str:$i:1}
It works for abcd/
:
$ bash last_ch.sh abcd/ /
It does not work for abcd*
:
$ bash last_ch.sh abcd* array.sh assign.sh date.sh dict.sh full_path.sh last_ch.sh
It lists the files in the current folder.
To access the last n characters of a string, we can use the parameter expansion syntax ${string: -n} in the Bash shell. -n is the number of characters we need to extract from the end of a string.
You can use string. back() to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string. rbegin() will give you an iterator to the last character.
To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.
${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol. When a parameter is referenced by a number, it is called a positional parameter.
Per @perreal, quoting variables is important, but because I read this post like 5 times before finding a simpler approach to the question at hand in the comments...
str='abcd/' echo "${str: -1}"
Output: /
str='abcd*' echo "${str: -1}"
Output: *
Thanks to everyone who participated in this above; I've appropriately added +1's throughout the thread!
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