Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last character of a string in a shell?

Tags:

string

bash

shell

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.

like image 879
thinker3 Avatar asked Jul 09 '13 07:07

thinker3


People also ask

How do I get the last 4 characters of a string in Bash?

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.

How do you reference the last character 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.

How do you get the first character of a string in Shell?

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.

What is ${} in Shell?

${} 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.


1 Answers

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!

like image 121
quickshiftin Avatar answered Sep 23 '22 12:09

quickshiftin