Chinaunix首页 | 论坛 | 博客
  • 博客访问: 63512
  • 博文数量: 17
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 18
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-17 22:52
文章分类
文章存档

2017年(17)

我的朋友

分类: LINUX

2017-07-13 16:04:05

原文地址:解读:bash去重复 作者:yinyuemi

原帖:
 
cat file
1 A
2 B
3 C
4 A
5 D
 
  1. #!/bin/bash
  2. s=$'\n'
  3. while read null str
  4. do
  5. [ "$s" == "${s/ $str}" ] && echo $str && s="$s $str"
  6. done

上面是原代码,我做了下修改,来展示整个程序执行的过程(为了更加明了,我将原来的s=$'\n',给为s="#"):

 

  1. #!/bin/bash
  2. s="#"
  3. while read null str
  4. do
  5. echo "s: " $s "|str: " $str "|null: " $null
  6. echo "if [ "$s" == " ${s/ $str} "]"
  7. if [ "$s" == "${s/ $str}" ]
  8. then
  9. echo "str: " $str "||" ${s/ str} && s="$s $str"
  10. else
  11. echo "s: " $s "|str: " $str "|null: " $null
  12. fi
  13. done

脚本执行结果:

 

  1. s: # |str: A |null: 1
  2. if [ # == # ]
  3. str: A || #
  4. s: # A |str: B |null: 2
  5. if [ # A == # A ]
  6. str: B || # A
  7. s: # A B |str: C |null: 3
  8. if [ # A B == # A B ]
  9. str: C || # A B
  10. s: # A B C |str: A |null: 4
  11. if [ # A B C == # B C ]
  12. s: # A B C |str: A |null: 4
  13. s: # A B C |str: D |null: 5
  14. if [ # A B C == # A B C ]
  15. str: D || # A B C

原来问题的关键就是"$s" == " ${s/ $str},这个判断。

${s/ $str}实际上是bash对字符串处理的一种方式,替换,即${var/a/b/} 将var中的a替换成b,当b为空时,可以直接写成${var/a}的形式。

利用这个bash处理字符串的功能,就可以实现去重复,很巧妙的设计!

 

阅读(2371) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~