Linux下的egrep如何忽略特定结尾文件/特定文件夹/二进制文件?

 手机用户2602880745 发布于 2022-11-01 04:16

描述问题

有三个需求(见标题), 而且这几个需求很常见
但是我搜索man文档,也按照它的指示做了,但是总感觉姿势不对(不符合预期结果)

然后Google了一番,结果无非和man文档差不多
所以我的问题可以转化为: 怎么读懂文档中关于exclude的部分?

根据我自己的理解,总结为以下几点:

  1. 使用shell通配符

  2. --exclude-from, --exclude-dir分别针对文件,文件夹. --exclude貌似是一个大的选项

  3. 针对二进制文件用-I, 但是grep怎么知道哪些是二进制文件? (应该有某种配置选项?)

比如有这几个情况,我构造的命令分别如下

  1. 忽略.pyc文件 --exclude-from="*.pyc"

  2. 忽略.svn目录 --exclude-dir="\.svn"

  3. 忽略二进制文件, -I (我对这个选项真是不理解)

上下文环境

  1. Linux Ubuntu16

  2. GNU grep 2.6.3

  3. 我的alias: alias grep='egrep --color=auto'

我工作时构造的命令: grep -r --exclude-dir="\.svn" 'KeyValue\b' ./
`

重现

  1. man grep

  2. 有.svn目录最好, .git目录也可以, 或其他

  3. 尝试使用grep的exclude的几个选项

  4. 查看预期结果

相关代码

摘抄grep的man文档中关于exclude的搜索结果

--exclude=GLOB
              Skip  files  whose  base  name  matches GLOB (using wildcard matching).  A file-name glob can use *, ?, and [...]  as wildcards, and \ to quote a wildcard or
              backslash character literally.

       --exclude-from=FILE
              Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude).

       --exclude-dir=DIR
              Exclude directories matching the pattern DIR from recursive searches.

报错信息

我构造的命令是grep -r --exclude-dir="\.svn" 'KeyValue\b' ./
报错信息为: 仍然会搜索.svn中的文件

相关截图

已经尝试哪些方法仍然没有解决(附上相关链接)

结果很好找,但是不知道为何我的结果有点不同
Google了

  1. grep ignore spcific directory

  2. grep exclude binary file

  3. grep exclude some file

  4. grep exclude pyc file

问题简化

2 个回答
  • 去掉 \

    grep -r --exclude-dir=".svn" 'KeyValue\b' ./
    

    --exclude-dir 里的路径应该使用通配符(wildcard),文本查找使用正则表达式(regular expression)。

    2022-11-01 11:26 回答
  • 用管道,比如这样?

    find -type f (-not -name '*ext') -and (-not -type d -name 'dir') | xargs -n1 -I{} grep --exclude=GLOB 'search_str' {}
    2022-11-01 11:31 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有