Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the last character in a string in bash?

I need to ensure that the last character in a string is a /

x="test.com/"

if [[ $x =~ //$/ ]] ; then
        x=$x"extention"
else
        x=$x"/extention"
fi

at the moment, false always fires.

like image 638
Mild Fuzz Avatar asked Oct 09 '13 12:10

Mild Fuzz


People also ask

How do I get the last character of a string in bash?

To access the last character of a string, we can use the parameter expansion syntax ${string: -1} in the Bash shell. In bash the negative indices count from the end of a string, so -1 is the index of a last character. Note: Space is required after the colon (:); otherwise it doesn't work.

How do you read the last character of a string?

Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.

How do you find the last occurrence of a character in a string in Linux?

strrchr() — Locate Last Occurrence of Character in String.

What is the last character of a string?

The end of the string is marked with a special character, the null character , which is simply the character with the value 0. (The null character has no relation except in name to the null pointer . In the ASCII character set, the null character is named NUL.)


1 Answers

Like this, for example:

$ x="test.com/"
$ [[ "$x" == */ ]] && echo "yes"
yes

$ x="test.com"
$ [[ "$x" == */ ]] && echo "yes"
$ 

$ x="test.c/om"
$ [[ "$x" == */ ]] && echo "yes"
$ 

$ x="test.c/om/"
$ [[ "$x" == */ ]] && echo "yes"
yes

$ x="test.c//om/"
$ [[ "$x" == */ ]] && echo "yes"
yes
like image 117
fedorqui 'SO stop harming' Avatar answered Sep 18 '22 00:09

fedorqui 'SO stop harming'