用 rg "tag" -g "*.c" -n 替代find -name *.c |xargs grep -rsn
rg(ripgrep)同时搜索 *.c 和 *.h 文件,可以使用多个 -g 参数:
rg "keyword" -g ".c" -g ".h"
例如:
rg "snprintf" -g ".c" -g ".h"
``
只会在 .c 和 .h 文件中搜索 snprintf。
其他常用写法
1. 搜索多个目录下的 .c/.h
rg "keyword" src include -g ".c" -g ".h"
2. 排除第三方目录
rg "keyword" </span>
-g ".c" </span>
-g ".h" </span>
-g "!vendor/" </span>
-g "!build/"
3. 只列出文件名
rg -l "keyword" -g ".c" -g ".h"
4. 显示匹配行号
rg -n "keyword" -g ".c" -g ".h"
5. 统计匹配次数
rg -c "keyword" -g ".c" -g ".h"
如果经常搜 C 代码,可以定义 alias:
alias rgc='rg -g ".c" -g ".h"'
以后直接:
rgc "PCIe"
rgc "handler_dispatch"
rgc "detect.active"
即可只在 .c/.h 文件中搜索。
To optimize searching for a string within
.c files, the primary bottleneck in your current command is that xargs grep -rsn redundant actions and inefficient pipelines.Recommended Alternative (Fastest)
Use dedicated search tools like
ripgrep (rg) or ack if available, as they use multi-threading and optimized regex engines:rg "tag" -g "*.c" -n
Optimized
find + grep CommandsIf you want to stick strictly to standard Unix tools, here are two optimized ways:
-
Using
find ... -exec(Avoidsxargsand quotes wildcard properly):
find . -type f -name "*.c" -exec grep -sn "tag" {} + -
Fixing your
xargspipeline:
find . -type f -name "*.c" -print0 | xargs -0 grep -sn "tag"
Key Improvements Made
-
Quoted
*.c: Prevents the shell from expanding*.cin the current directory before passing it tofind. -
Removed
-r(recursive) fromgrep: Sincefindalready recursively discovers the.cfiles, runninggrep -ron every file passed byxargscauses unnecessary directory traversal overhead. -
Removed
-s(suppress errors) if unneeded: Dropped unless you are scanning files with permission restrictions. -
-print0andxargs -0: Safely handles filenames containing spaces, newlines, or special characters. -
-exec ... {} +: Passes multiple files to a singlegrepprocess call (similar toxargs), reducing process creation overhead.
Time is like a fleeting show!
posted on 2026-09-03 15:18 ENGINEER-F 阅读(25) 评论(0) 收藏 举报
浙公网安备 33010602011771号