如何使用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_nextsets 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 theprint_restloop 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
相关产品推荐
相关产品推荐

