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

如何用grep提取日志行指定部分并合并显示?

Solution to Extract Clean Log Lines While Tailing

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 -o extracts 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 -E filters only lines that contain both [TEXT] and [OTHERTEXT] (avoids processing irrelevant lines).
  • sed -E uses capture groups: \1 grabs everything up to [TEXT], \2 grabs 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:

  • -n tells sed not to print lines by default.
  • The s///p substitution 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:34:23