问题描述
我想搜索目录(不包括包含某些单词的路径,最好是正则表达式模式),并找到内容与我的查询相匹配的所有文件(最好是正则表达式模式, d区分大小写),并在2个特定日期之间进行了修改。
基于this answer,我当前的命令是:
find /mnt/c/code -type f -mtime -100 -mtime +5 -print0 |
xargs -0 grep -l -v "firstUnwantedTerm" 'mySearchTerm'
显然,此查询不会排除所有包含“ firstUnwantedTerm”的路径。
此外,如果结果可以按修改后的日期时间降序排序,并显示:它们的修改时间,完整文件名和搜索查询(可能会以不同的颜色显示,控制台)周围的某些上下文。
here中的 grep -rnwl --exclude='*firstUnwantedTerm*' '/mnt/c/code' -e "mySearchTerm"
似乎也朝着正确的方向迈出了一步,因为它似乎正确排除了我的排除条件,但它不会按修改的日期时间进行过滤,并且不会当然会输出所有所需的字段。
解决方法
这是快速又肮脏的,没有按日期排序,但是在每个匹配项和彩色匹配项之前/之后都有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' {} \;