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

如何使用sed提取首个BEGIN与最后一个END之间的文本?

Sed: Extract Content from First "BEGIN" to Last "END"

Your original command sed -n -e '/^BEGIN$/,/^END$/p' logs.txt works by matching each individual pair of BEGIN and the immediately following END—that’s why it only pulls out two separate blocks instead of the full range from the first BEGIN to the last END.

Working Solution Command

To capture everything from the first occurrence of BEGIN all the way to the last occurrence of END, use this sed command:

sed -n '1,/BEGIN/{/BEGIN/!d}; /END/{p;q}; p' logs.txt

Breakdown of How It Works

Let’s break down each part to make it clear:

  • -n: Turns off sed’s default behavior of printing every line, so we only output what we explicitly specify.
  • 1,/BEGIN/{/BEGIN/!d}: Handles lines from the start of the file up to the first BEGIN:
    • For any line in this range that doesn’t contain BEGIN, we delete it (!d). This skips all pre-BEGIN lines and keeps only the first line with BEGIN.
  • /END/{p;q}: When we hit a line with END:
    • Print the line (p), then immediately quit sed (q). Since sed processes lines top-to-bottom, this ensures we stop at the final END in the file.
  • p: Prints all lines that fall between the first BEGIN and the last END—these lines don’t trigger the previous two rules, so we explicitly print them.

Test with Your Input

Given your input (formatted as multi-line for clarity):

line1
BEGIN line2 line3 END line4
line5 BEGIN line6 line7 ENDED END line8
END line9
line10

The command will output exactly your expected result:

BEGIN line2 line3 END line4
line5 BEGIN line6 line7 ENDED END line8
END line9

Alternative State-Tracking Approach

If you prefer a more explicit state-based method, this version uses sed’s branch labels to track when we’re in the target range:

sed -n '/BEGIN/{:track; p; n; /END/{p; q}; b track}' logs.txt
  • /BEGIN/{:track; p; n}: When BEGIN is found, set a label track, print the line, then read the next line.
  • /END/{p; q}: If the new line contains END, print it and quit.
  • b track: If not, jump back to the track label to keep printing lines until we hit the final END.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:37:56