haishi 发表于 2018-8-19 09:07:13

linux shell 脚本之深入浅出的grep的用法

  今天在纠结grep用法时候,由于讲解的教材比较少,纠结了较长的时间。最终还是攻下了,所以拿出来给大家分享。
  grep
  显示匹配一个或多个模式的文本行,时常会作为管道后的第一步,以便对匹配上的数据做进一步处理。
  最常见用法,查询文件内字符串
  # grep root /etc/shadow
  root:$1$HFDnk5hm$DSAc4IUls1yUyocXFNQ.A.:15141:0:99999:7:::
  #
  参数
  -E使用扩展正则表达式进行匹配,使用grep –E 代替传统的扩展正则表达式 egrep
  扩展正则表达式和正则表达式的区别:(-E选项的作用)
  +匹配一个或多个先前的字符
  # touch test
  # vim test
  aaaredhat
  bbbredhat
  yyyredhat
  zzzredhat
  redhataaa
  redhatbbb
  redhatyyy
  redhatzzz
  :wq
  # cat test|grep –E '+redhat'
  aaaredhat
  bbbredhat
  #
  # cat test|grep -E 'redhat+'
  redhatyyy
  redhatzzz
  #
  当去掉-E选项的时候,正则表达式是不支持这样查询的。
  # cat test|grep 'redhat+'
  #
  ?   匹配零个或多个先前的字符
  # cat test|grep -E 'r?aaa'
  aaaredhat
  redhataaa
  # cat test|grep 'r?aaa'
  #
  a|b|c匹配a或b或c
  # cat test|grep -E 'b|z'
  bbbredhat
  zzzredhat
  redhatbbb
  redhatzzz
  # cat test|grep 'b|z'
  #
  () 分组符号
  # cat test|grep -E 'redha(tz|ta)'
  redhataaa
  redhatzzz
  # cat test|grep 'redha(tz|ta)'
  #
  x{m} 重复字符x,至少m次   (如果用正则表达式,格式为x\{m,\})
  # cat test|grep -E 'a{3}'
  aaaredhat
  redhataaa
  # cat test|grep 'a\{3,\}'
  aaaredhat
  redhataaa
  #
  -F使用固定字符串进行匹配 grep –F 取代传统的 fgrep 。 使用正则表达式; 默认情况下 grep 使用的就是正则表达式,grep = grep –F
  -e通常,第一个非选项的参数会指定要匹配的模式,这个模式以-号开头时,grep就会混淆,而-e选项就将它确定为参数
  # cat test|grep -e '-test'
  -test
  # cat test|grep '-test'
  grep:无效选项 -- t
  Usage: grep ... PATTERN ...
  Try `grep --help' for more information.
  #
  -i模式匹配时,忽略大小写
  # cat test|grep -i test
  -test
  -TEST
  #
  -l列出匹配模式的文件名称(列出当前目录下含有test字符串的文件)
  # grep -l 'test' ./*
  ./test
  ./test2
  #
  -q静默模式,如果匹配成功,则grep会离开,不显示匹配。
  # grep test ./test
  -test
  # grep -q test ./test
  #
  -s不显示错误信息
  -v显示不匹配的项
  # cat test|grep test
  -test
  # cat test|grep -v test
  -TEST
  #

页: [1]
查看完整版本: linux shell 脚本之深入浅出的grep的用法