如何用grep提取日志行指定部分并合并显示?
Hey Tobias, let's work through this log parsing problem—since you want to prioritize learning grep, we'll start there, then cover awk and sed alternatives too. All these methods work with tail -f for real-time log monitoring.
Grep + Paste (Pure Grep-Based Approach)
Your initial attempt with grep -o outputs each match on a new line, but we can fix that by merging those lines with paste:
tail -f your_log_file.log | grep -o -e '.*\[TEXT\]' -e '\[OTHERTEXT\].*' | paste -d' ' - -
How it works:
grep -oextracts two parts per log line: everything up to[TEXT], and everything from[OTHERTEXT]to the end. Each part gets its own line.paste -d' ' - -takes every pair of lines and joins them with a single space, giving you the combined line you want.
Grep + Sed (Filter First, Clean Up Second)
If you prefer to first filter relevant lines with grep, then strip the unwanted middle section with sed:
tail -f your_log_file.log | grep -E '.*\[TEXT\].*\[OTHERTEXT\].*' | sed -E 's/(.*\[TEXT\]).*(\[OTHERTEXT\].*)/\1 \2/'
How it works:
grep -Efilters only lines that contain both[TEXT]and[OTHERTEXT](avoids processing irrelevant lines).sed -Euses capture groups:\1grabs everything up to[TEXT],\2grabs everything from[OTHERTEXT]onwards. We replace the entire line with these two groups separated by a space.
Awk (Straightforward Field/Pattern Handling)
Awk is great for structured text manipulation, and this one-liner directly targets the parts you care about:
tail -f your_log_file.log | awk '{ match($0, /(.*\[TEXT\])(.*)(\[OTHERTEXT\].*)/, parts) print parts[1], parts[3] }'
How it works:
- The
match()function uses regex capture groups to split the line into three parts: your desired first segment, the unwanted middle, and your desired second segment. - We simply print the first and third groups separated by a space.
A more concise awk variant (no explicit capture groups):
tail -f your_log_file.log | awk '{ split($0, a, /\[TEXT\]/) split(a[2], b, /\[OTHERTEXT\]/) print a[1] "[TEXT] [OTHERTEXT]" b[2] }'
Sed (Direct Line Transformation)
If you want to skip grep entirely, sed can handle both filtering and cleaning in one step:
tail -f your_log_file.log | sed -nE 's/(.*\[TEXT\]).*(\[OTHERTEXT\].*)/\1 \2/p'
How it works:
-ntells sed not to print lines by default.- The
s///psubstitution replaces the unwanted middle section and prints only the modified lines that match the pattern.
Hope these solutions fit your needs—feel free to ask if you want to dive deeper into any of the regex or command details!
内容的提问来源于stack exchange,提问作者ximarin

