Nicol
June 4, 2009, 8:24am
1
hi
i try to test the last character in a variable (here $i )
assume i=kljlkjlkA it should be KO and lkjljjlT KO
if [ "echo $i|grep A$" ]
then
echo "ending with A"
else
echo "no A at the end"
fi
whether i is ending or not with A i got "no A at the end"
i tried with simple [ double this is the same , i think the pb is with the Interpretation of A$
thanks in advance
Christian
It's not that simple, I daresay - but possible, of course:
#! /bin/bash
INPUT="$1"
LENGTH=${#INPUT}
if [ "${INPUT:$(($LENGTH-1)):1}" = "O" ]
then
echo "good"
else
echo "bad"
fi
exit 0
[house@leonov] sh test.bash 'kljlkjlkA it should be KO and lkjljjlT KO'
good
Here are two ways of doing it. Both ways work in bash and ksh93
i=kljlkjlkA
if [[ ${i: -1} == "A" ]]
then
echo "ending with A"
else
echo "no A at the end"
fi
if [[ $i =~ A$ ]]
then
echo "ending with A"
else
echo "no A at the end"
fi
Nicol
June 4, 2009, 8:54am
4
thanks but it doesn't work for me :
# sh test.bash 'kljlkjlkA it should be KO and lkjljjlT KO'
test.bash[6]: "${INPUT:$(($LENGTH-1)):1}": bad substitution
i'm in ksh but in bash it's the same !
regards
Christian
-----Post Update-----
Thanks to help me :
i=kljlkjlkA
if [[ ${i: -1} == "A" ]]
then
echo "ending with A"
else
echo "no A at the end"
fi
=> i got :
# test.ksh
test.ksh: ${i: -1}: bad substitution
if [[ $i =~ A$ ]]
then
echo "ending with A"
else
echo "no A at the end"
fi
==> i got :
test.ksh
test.ksh: syntax error at line 1 : `=~' unexpected
regards