如何在日志文件中查找根目录下2级深度的文件路径字符串
Got it, let's solve this problem—since find is for locating actual files on your filesystem, it won't help with parsing log strings. Instead, we'll use text-processing tools like grep or awk to target exactly the path format you need: /xxx/xxx/xxx.xxx (root + 2 directories + filename, no deeper levels).
Method 1: Use grep with Regular Expressions
This is the quickest way if you just need to extract matching paths. We'll use a regex that matches the exact depth and excludes deeper paths.
Command:
grep -oE '/[^/]+/[^/]+/[^/]+(?!/)' your_log_file.log
Breakdown:
-o: Only output the matched part of the line (instead of the whole line)-E: Enable extended regular expressions/[^/]+: Matches a directory segment (starts with/, followed by one or more non-/characters)- We repeat this twice to cover the two directory levels, then add
/[^/]+for the filename (?!/): A negative lookahead that ensures there's no trailing/after the filename—this prevents partial matches of deeper paths (like/a/b/cfrom/a/b/c/d.txt)
If your logs have paths embedded in longer lines and you want to avoid false positives (e.g., paths with extra characters attached), you can tweak the regex to match word boundaries:
grep -oE '\b/[^/]+/[^/]+/[^/]+(?!/)\b' your_log_file.log
Method 2: Use awk for More Flexibility
If you need to do additional processing (like counting paths, filtering by other log fields), awk is a better choice. We'll split paths by / to check their depth explicitly.
One-Liner Command:
awk '{ while (match($0, /\/[^\/]+\/[^\/]+\/[^\/]+(?!\/)/, path_arr)) { print path_arr[0] $0 = substr($0, RSTART + RLENGTH) } }' your_log_file.log
Breakdown:
match($0, regex, path_arr): Finds the first matching path in the current line and stores it inpath_arr[0]print path_arr[0]: Outputs the matched pathsubstr($0, RSTART + RLENGTH): Truncates the line to the part after the matched path, so we can find multiple paths in one line- The regex works the same way as the
grepversion—ensuring we only get 2-level deep root paths
Alternatively, if you want to split paths and check depth numerically (useful for debugging edge cases):
awk '{ for (i=1; i<=NF; i++) { split($i, parts, "/") # A valid 2-level path will split into 4 elements (e.g., "/a/b/c.txt" → ["", "a", "b", "c.txt"]) if ($i ~ /^\// && length(parts) == 4 && parts[4] != "") { print $i } } }' your_log_file.log
Note: This assumes paths are separated by whitespace. If your paths contain spaces, use the match method above instead.
Key Note
Remember: find's maxdepth/mindepth operate on the filesystem's directory structure. When parsing log strings, we're dealing with text patterns, so text-processing tools are the right approach here.
内容的提问来源于stack exchange,提问作者Eggiderm

