原帖:
cat file
1 A
2 B
3 C
4 A
5 D
- #!/bin/bash
- s=$'\n'
- while read null str
- do
- [ "$s" == "${s/ $str}" ] && echo $str && s="$s $str"
- done
上面是原代码,我做了下修改,来展示整个程序执行的过程(为了更加明了,我将原来的s=$'\n',给为s="#"):
- #!/bin/bash
- s="#"
- while read null str
- do
- echo "s: " $s "|str: " $str "|null: " $null
- echo "if [ "$s" == " ${s/ $str} "]"
- if [ "$s" == "${s/ $str}" ]
- then
- echo "str: " $str "||" ${s/ str} && s="$s $str"
- else
- echo "s: " $s "|str: " $str "|null: " $null
- fi
- done
脚本执行结果:
- s: # |str: A |null: 1
- if [ # == # ]
- str: A || #
- s: # A |str: B |null: 2
- if [ # A == # A ]
- str: B || # A
- s: # A B |str: C |null: 3
- if [ # A B == # A B ]
- str: C || # A B
- s: # A B C |str: A |null: 4
- if [ # A B C == # B C ]
- s: # A B C |str: A |null: 4
- s: # A B C |str: D |null: 5
- if [ # A B C == # A B C ]
- str: D || # A B C
原来问题的关键就是"$s" == " ${s/ $str},这个判断。
${s/ $str}实际上是bash对字符串处理的一种方式,替换,即${var/a/b/} 将var中的a替换成b,当b为空时,可以直接写成${var/a}的形式。
利用这个bash处理字符串的功能,就可以实现去重复,很巧妙的设计!
阅读(2436) | 评论(0) | 转发(0) |