求助:如何用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.
Solution 1: Use Grep's --include Flag (Recommended)
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

