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

如何使用sed删除模式第二次匹配之前的所有行?

Skip First Match and Print From Second "third" in sed

Nice question! You can definitely tweak that sed command to skip the first "third" match and start printing from the second one. Let me walk you through a couple of solid ways to do this:

Method 1: Labeled Branching (Readable & Flexible)

This approach uses sed's built-in labeling and branching to track when we hit the second occurrence of "third":

cat file | sed -n '
/third/{
    # First match: keep skipping lines until we find the next "third"
    :search_next
    n
    /third/!b search_next
    # Found the second "third" — print it and everything after
    p
    :print_rest
    n
    p
    b print_rest
}'

Breakdown:

  • When we first hit a line with "third", we jump into the block.
  • :search_next sets a loop label: we read the next line (n), and if it doesn't have "third", we loop back to keep searching (/third/!b search_next).
  • Once we find the second "third", we print it (p), then enter the print_rest loop to print every remaining line until the end of the file.

Method 2: Concise One-Liner

If you want a shorter command that does the same thing, here's a condensed version:

cat file | sed -n '/third/{:a;n;/third/!ba;:b;p;n;b b}'

Quick Explanation:

  • /third/{ ... }: Triggers on the first "third" line.
  • :a;n;/third/!ba: Loops to skip lines until we find the second "third".
  • :b;p;n;b b: Once we hit the second match, this loop prints the current line, reads the next, and repeats until EOF.

Example Output

If your file contains these lines:

first
second
third
fourth
third
fifth
sixth

Running either command will give you exactly what you're after:

third
fifth
sixth

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:15:49