用 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:

Bash
 
rg "tag" -g "*.c" -n

Optimized find + grep Commands

If you want to stick strictly to standard Unix tools, here are two optimized ways:

  1. Using find ... -exec (Avoids xargs and quotes wildcard properly):

    Bash
     
    find . -type f -name "*.c" -exec grep -sn "tag" {} +
    
  2. Fixing your xargs pipeline:

    Bash
     
    find . -type f -name "*.c" -print0 | xargs -0 grep -sn "tag"
    

Key Improvements Made

  • Quoted *.c: Prevents the shell from expanding *.c in the current directory before passing it to find.
  • Removed -r (recursive) from grep: Since find already recursively discovers the .c files, running grep -r on every file passed by xargs causes unnecessary directory traversal overhead.
  • Removed -s (suppress errors) if unneeded: Dropped unless you are scanning files with permission restrictions.
  • -print0 and xargs -0: Safely handles filenames containing spaces, newlines, or special characters.
  • -exec ... {} +: Passes multiple files to a single grep process call (similar to xargs), reducing process creation overhead.

posted on 2026-09-03 15:18  ENGINEER-F  阅读(25)  评论(0)    收藏  举报