Remove all repeated Characters in a String

In this blog, sharing the code to remove consecutively repeated characters in a String. Consider a String “allabouttechnologies” . Here, l and t are repeated Characters. So, after applying logic, it will be like “alaboutechnologies“.

str=”alllabouttechnologies” ##Sample String
newstr=” ##new Blank String
n=${#str} ##length of a Sample String
PrevChar=${str:0:1} ##First Character of a String
i=1
while [[ $i -le $n ]] ##Looping Character by Character
do
NextChar=${str:$i:1}
if [[ $PrevChar == $NextChar ]] ##if two consecutive Character matches, it will remove or ignore the matched one and keep repeated Character once
then
echo “Ignore this Character: “$NextChar
else
newstr=${newstr}${PrevChar} ##merging only non-repeated Characters
fi
PrevChar=$NextChar
i=$(( $i + 1))
done
echo $newstr

Related posts