grep 技巧10则

grep 技巧10则 (2011-10-06 22:15)
标签:   grep tips 技巧  分类:  linux tools

warning:文中提到的选项如果posix未指定,会特殊说明。

1 多个关键字查找
    1.1 使用-e

  1. grep -e 'stdio\.h' -e 'stdlib\.h' /usr/include/*.h

    1.2 使用-f file
        将关键字以行方式保存在一个文件中
    1.3 使用元字符 \|
  1. grep 'stdio\.h\|stdlib.h' /usr/include/*.h

    1.4 多关键字 and 查找
  1. grep 'stdio\.h\|stdlib.h' /usr/include/*.h


2. 单词匹配
    -w(gnu 选项)
  1. grep -w 'main' /usr/include/*.h

    \<\>
  1. grep '\<main\>' /usr/include/*.h


2.善用 -E
    -E选项启用 extended expression,正则写起来更加灵活
        例如匹配一行内两个连续重复the或that或and或or
  1. man gcc | grep -E '(\<the\>|\<that\>|\<and\>|\<or\>) \1'

3 多文件查找
  1. grep -l 'main' *.c


4 忽略大小写 -i
  1. grep -i -w 'sTAt' /usr/include/*.h

5 递归查找 -r(posix 未说明)
  1. grep -i -w -r -E 'error|failed|failure' /var/log |less


6 显示匹配行周围行 (posix 未说明)
    B/A/C(before/after/context
    -B n
    -A n
    -C n
  1. grep -w -i -C 3 'struct stat' /usr/include/*.h

7 取反-v
  1. grep -v -w 'hello' filename

    如果没有取反,世界将不再美丽
8 匹配数 -c
  1. echo aaaa | grep -c 'a'

    这个输出是1!因为grep是行匹配的

9 输出文件名 -l
  1. grep -l -r -i -w 'filename_max' /usr/include/*.h


10 只输出匹配部分-o (gnu 选项)
  1. echo abcddf |grep -o 'dd'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值