狼狼 发表于 2018-8-23 07:48:21

shell 练习题

  有一个文件,里面有二列,第一列ip地址,第二列是时间,同一个ip可能出现多次,但时间不同.
  文件类似下面的样子:
  192.168.1.1   12:12
  193.13.34.4    12:45
  192.168.1.1    18:02
  134.345.34.34   19:21
  196.196.1.1   21:15
  192.168.1.1    22:15
  192.13.34.4    19:18
  192.13.34.5   21:18
  192.168.1.1   21:18
  现要求写一脚本,显示出现最多的ip top 3
  命令: cat mytime.txt|grep -v '^$' | awk '{print $1}'|sort|uniq -c|sort -r | head -3
  命令解析: grep -v '^$' 过滤掉无用的空行      awk '{print $1}'展示IP地址一列
  sort首先排序之后调用uniq -c 记录一共出现多少次(必须先排序)
  sort -r 按照由大到小排序   head -3 只展示前三列。
  .处理一下文件内容,将域名取出并进行计数排数,如处理:
  http://www.baidu.com/index.html
  http://ww.baidu.com/1.html
  http://www.baidu.com/2.html
  http://post.baidu.com/index.html
  http://mp3.baidu.com/index.html
  http://www.baidu.com/3.html
  http://post.baidu.com/2.html
  得到如下结果:域名的出现次数,域名
  4   www.baidu.com
  2   post.baidu.com
  1   mp3.baidu.com
  命令: cat myweb.txt | grep -v "^$"|sed's;\/\/;\/;'|awk -F / '{print $2}'|sort|uniq -c|sort -r
  命令解析:grep -v "^$"过滤掉无用的空行
  sed's;\/\/;\/;' 将两个反斜线//替换为一个反斜线/
  awk -F / '{print $2}' 设定分隔符为反斜线/输出第二项
  sort首先排序之后调用uniq -c 记录一共出现多少次(必须先排序)
  sort -r 按照由大到小排序
  写一个登录shell文件,输入6次错误的用户名或密码不能登录,输入xxx用户,xxx密码登录成功
  #! /bin/bash
  index=0
  right="true"
  maxtimes=3
  #注意这里多个条件的判断形式
  while [ "$right" == "true" -a $index -lt $maxtimes ]
  do
  read -p "please input your user name:" username
  read -p "please input your user password:" userpassword
  #注意这里多个条件的判断形式
  if [ "$username" == "root" -a "$userpassword" == "root" ]
  then
  right="false"
  else
  echo "your user name or password is not right"
  fi
  ((index++ ))
  if [ $index -eq $maxtimes ]
  then
  echo "you have input more than the max times"
  fi
  done
  1、数据文件格式如下:
10123456      ch1  20143456      ch3
  30123456      ch2
  40133456      ch1
  50163456      ch1
  60113456      ch1
  70123456      ch2
  80123456      ch2
  90123456      ch4
  100123456      ch3
  110123456      ch1
  120123456      ch1
  要按照第8列,分类,把文件拆分,分别写入不同的文件里。文件名为:ch1.txt、ch2.txt、ch3.txt。
  filename="/home/song/myinfo.txt"
  while read line
  do
  #注意这里得到管道的执行结果
  Name=$(echo $line|grep -v '^$'|awk '{print $7}')
  if [ "$Name" != "" ]
  then
  echo $line>> $Name
  fi
  done < $filename


页: [1]
查看完整版本: shell 练习题