用shell处理以下内容 1、按单词出现频率降序排序! 2、按字母出现频率降序排序!

排序的字符串如下: the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support

此题目有多种解法,sed、awk、tr等等,都可以解决此题,命令运用灵活多变。

编写shell脚本

解法1:

#!/bin/bash

###-------------CopyRight-------------  
#   Name:sort string
#   Version Number:1.0  
#   Type:sh  
#   Language:bash shell  
#   Date:2018-05-09  
#   Author:sandy 
#   QQ:442656067
#   Email:eeexu123@163.com 

str="the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"
#no1按单词出现的频率降序排序
word(){
  echo $str|sed 's#[^a-zA-Z]#\n#g'|grep -v "^$"|sort|uniq -c|sort -rn -k1
}

#no2按字母出现的频率降序排序
string(){
  echo $str|grep -o "."|egrep -v "[^a-zA-Z]"|sort|uniq -c|sort -rn -k1
}

menu(){
  cat <<END
  1.按单词出现的频率降序排序
  2.按字母出现的频率降序排序
END
  read -p "Pls you choose num:" num
}
menu

usage(){
  echo "USAGE:You muset choose 1 or 2"
  exit 1
}

case "$num" in
  1)
    word
    ;;
  2)
    string
    ;;
  *)
    usage
esac

解法2:

#!/bin/bash

##-------------CopyRight-------------  
#   Name:sort string
#   Version Number:1.1 
#   Type:sh  
#   Language:bash shell  
#   Date:2018-05-09  
#   Author:sandy 
#   QQ:442656067
#   Email:eeexu123@163.com  

str="the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"
#no1按单词出现的频率降序排序
word(){
  echo $str|tr ' ' '\n'|sort|uniq -c|sort -rn -k1
}

#no2按字母出现的频率降序排序
string(){
  echo $str|sed -r 's#(.)#\1\n#g'|egrep -v "[^a-zA-Z]|^$"|sort|uniq -c|sort -rn -k1
}

menu(){
  cat <<END
  1.按单词出现的频率降序排序
  2.按字母出现的频率降序排序
END
  read -p "Pls you choose num:" num
}
menu

usage(){
  echo "USAGE:You muset choose 1 or 2"
  exit 1
}

case "$num" in
  1)
    word
    ;;
  2)
    string
    ;;
  *)
    usage
esac

执行上述脚本,如果如下:

[root@mysql01 shell]# sh no_20.sh
1.按单词出现的频率降序排序
2.按字母出现的频率降序排序
Pls you choose num:1
2 support
2 squid
2 and
1 users
1 toassist
1 the
1 sections
1 resources
1 provides
1 project
1 Please
1 of
1 number
1 more
1 installations
1 infomation
1 implement
1 for
1 documentation
1 design
1 browsethe
1 a
[root@mysql01 shell]# sh no_20.sh
1.按单词出现的频率降序排序
2.按字母出现的频率降序排序
Pls you choose num:2
19 s
17 e
16 o
14 t
12 n
12 i
11 r
9 a
8 u
7 p
7 d
6 m
4 l
4 c
3 f
2 q
2 h
2 b
1 w
1 v
1 P
1 j
1 g

posted @ 2018-05-15 17:14  启云  阅读(1433)  评论(0编辑  收藏  举报