grep - 如何搜索在特定日期之间修改的 Linux 文件的内容

标签 grep find full-text-search

我想搜索一个目录(不包括包含任何特定单词的路径,最好是正则表达式模式)并查找内容与我的查询匹配的所有文件(最好是正则表达式模式,我' d 不区分大小写)并在 2 个特定日期之间进行了修改。

基于this answer ,我当前的命令是:

find /mnt/c/code -type f -mtime -100 -mtime +5 -print0 |
xargs -0 grep -l -v "firstUnwantedTerm" 'mySearchTerm'

显然这个查询并没有排除所有包含“firstUnwantedTerm”的路径。

另外,如果结果可以按修改日期时间降序排序,并显示:它们的修改时间、完整文件名和搜索查询(可能在搜索结果中以不同的颜色显示),我会很高兴。控制台)被看到它的一些上下文所包围。

grep -rnwl --exclude='*firstUnwantedTerm*' '/mnt/c/code' -e "mySearchTerm" 来自 here从某种意义上说,它似乎也是朝着正确方向迈出的一步,它似乎正确排除了我的排除术语,但它不会按修改的日期时间进行过滤,当然也不会输出所有所需的字段。

最佳答案

这只是快速而肮脏的,没有按日期排序,但在每个匹配之前/之后有 3 行上下文和彩色匹配:

find ~/mnt/c/code -type f -mtime -100 -mtime +5 | grep -v 'someUnwantedPath' | xargs -I '{}' sh -c "ls -l '{}' && grep --color -C 3 -h 'mySearchTerm' '{}'"

分成几部分并进行一些解释:

# Find regular files between 100 and 5 days old (modification time)
find ~/mnt/c/code -type f -mtime -100 -mtime +5 |

  # Remove unwanted files from list
  grep -v 'someUnwantedPath' |

  # List each file, then find search term in each file,
  # highlighting matches and
  # showing 3 lines of context above and below each match
  xargs -I '{}' sh -c "ls -l '{}' && grep --color -C 3 -h 'mySearchTerm' '{}'"

我想你可以从这里拿走它。当然,这可以做得更漂亮并满足您的所有要求,但我只有几分钟的时间,让 UNIX 专家来打败我,让整个事情变得 200% 更好。


更新:版本 2 不带 xargs,仅使用一个 grep 命令:

find ~/mnt/c/code -type f -mtime -30 -mtime +25 ! -path '*someUnwantedPath*' -exec stat -c "%y %s %n" {} \; -exec grep --color -C 3 -h 'mySearchTerm' {} \;

! -path '*someUnwantedPath*' 过滤掉不需要的路径,两个 -exec 子命令列出候选文件,然后显示 grep 结果(也可以是空),就像以前一样。请注意,我从使用 ls -l 更改为 stat -c "%y %s %n"以便列出文件日期、大小和名称(只需修改为你希望)。

再次,为了便于阅读,添加了额外的换行符:

find ~/mnt/c/code
  -type f
  -mtime -30 -mtime +25
  ! -path '*someUnwantedPath*'
  -exec stat -c "%y %s %n" {} \;
  -exec grep --color -C 3 -h 'mySearchTerm' {} \;

关于grep - 如何搜索在特定日期之间修改的 Linux 文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63549087/

相关文章:

ruby-on-rails - Rails on Postgresql FullText Index 已经构建了 20 个小时。那是正常的吗?

mysql - MySQL全文搜索如何工作?

Postgresql - 全文搜索索引 - 意外的查询结果

linux - 将 grep 的输出写入 Linux 上的文件?

sed - bash 在每个空格前添加反斜杠?

command-line - 字符串搜索 : Using find/grep, 忽略 .git 和其他目录

java - 找不到符号—符号: method lastIndexOf(java.lang.String) location: class java.util.Scanner

linux - 正则表达式匹配 IP 地址但忽略本地主机

linux - 如何在 Linux 中同时运行 find 和 cp 命令?

regex - OS X 在带有正则表达式数字的 bash 中查找\d 未产生预期结果