如何从Bash中的字符串中删除重复的字符? [英] How to remove duplicated characters from string in Bash?
本文介绍了如何从Bash中的字符串中删除重复的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
cabbagee
我想删除重复的字符.如果我使用tr -s,它将删除序列中的重复字符.但是我想要的输出是
I want to delete duplicate charaters. If I use tr -s it will remove duplicate characters in the sequence. But my desired output is
cabge
感谢任何人都可以帮助我.
Appreciate if anyone can help me with that.
提供的答案是正确的,但是我无法使用awk,所以我使用了:
The answer provided was right but I was not able to use awk so I used:
#!/usr/bin/bash
key=$1
len=${#key}
mkey=""
for (( c=0; c<len; c++ ))
do
tmp=${key:$c:1}
echo $mkey | grep $tmp >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "Found $tmp in $mkey"
else
mkey+=$tmp
fi
done
echo $mkey
推荐答案
可以使用 awk
吗?
awk -v FS="" '{
for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str)
}
END {print str}' <<< "cabbagee"
cabge
其他方式的结合:
gnu awk
:
Couple of other ways:
gnu awk
:
awk -v RS='[a-z]' '{str=(++a[RT]==1?str RT: str)}END{print str}' <<< "cabbagee"
cabge
awk -v RS='[a-z]' -v ORS= '++a[RT]==1{print RT}END{print "\n"}' <<< "cabbagee"
cabge
gnu sed
和 awk
:
gnu sed
and awk
:
sed 's/./&\n/g' <<< "cabbagee" | awk '!a[$1]++' | sed ':a;N;s/\n//;ba'
cabge
这篇关于如何从Bash中的字符串中删除重复的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文