You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用grep命令递归搜索目录及子目录下的日志文件关键词

Fixing Recursive Log File Search with Grep

Hey there! I totally get why your current command isn't working—let me clear up what's happening and show you the right ways to search all .log files, including those in subdirectories.

Why Your Original Command Fails

When you run grep -r -H "Keyword" *.log, your shell first expands *.log into a list of only .log files in your current directory. The -r flag in grep would normally traverse subdirectories, but since you've passed it specific filenames (the current directory's .logs), it won't look for .log files in child folders anymore.

Modern GNU Grep has a built-in flag to filter files during recursion. Just specify the file pattern you want to target and start the search from the current directory (.):

grep -r -H --include="*.log" "Keyword" .

Let's break down the key parts:

  • --include="*.log": Tells grep to only consider files matching this pattern while recursing
  • .: Starts the search from the current directory (you can replace this with a specific path if needed)
  • -r: Recursively traverses all subdirectories
  • -H: Prints the filename along with matching lines (useful for knowing where the hit came from)

Solution 2: Fallback with find + grep

If you're using an older grep version that doesn't support --include (like some BSD systems), use find to locate all .log files first, then pipe them to grep:

find . -type f -name "*.log" -exec grep -H "Keyword" {} +
  • find . -type f -name "*.log": Finds all regular files (-type f) named like .log in the current directory and subdirectories
  • -exec grep -H "Keyword" {} +: Passes all the found files to grep in batches (more efficient than -exec ... \; which runs grep once per file)

Bonus: Exclude Specific Directories

If you want to skip certain folders (like node_modules or temp), add the --exclude-dir flag to the grep command:

grep -r -H --include="*.log" --exclude-dir="temp" --exclude-dir="node_modules" "Keyword" .

内容的提问来源于stack exchange,提问作者Sudhakar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:18:05