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

如何保留每个Modify块首行并删除后续Modify行?sed命令求助

Solution to Keep Only the First Modify: Line per File: Entry

Got it, let's fix this problem. You want to retain the first Modify: line that follows each File: entry, and discard any subsequent consecutive Modify: lines. Your initial sed attempts didn't work because they either deleted all Modify: lines or used invalid syntax for block-specific line numbering. Here are two reliable approaches:

1. Using sed with a State Flag

This uses sed's hold space to track whether we've already kept the first Modify: line for the current File: entry:

sed '/^ File:/{h;p;b};/^ Modify:/{x;/./{x;d};x;p;h}' sample.txt

How it works:

  • When we hit a line starting with File::
    • h: Save the line to the hold space (sets our "waiting for first Modify" flag)
    • p: Print the File: line
    • b: Skip the rest of the script for this line
  • When we hit a line starting with Modify::
    • x: Swap the pattern space (current line) with the hold space
    • /./{x;d}: If the hold space isn't empty (meaning we already kept a Modify: line for this File:), swap back and delete the current line
    • If the hold space is empty (first Modify: line for this File:), swap back, print the line, and save it to the hold space (h) to mark that we've already kept one

2. Using awk (More Intuitive Syntax)

awk makes state tracking straightforward with variables:

awk '/^ File:/ {print; keep_modify=1; next} /^ Modify:/ {if (keep_modify) {print; keep_modify=0} next} 1' sample.txt

How it works:

  • When a File: line is found: print it, set keep_modify to 1 (we want to keep the next Modify: line), then move to the next line
  • When a Modify: line is found: if keep_modify is 1, print the line and set keep_modify to 0 (so subsequent Modify: lines are skipped); otherwise, skip the line
  • The final 1 ensures any other lines (if present) are printed (not necessary for your input, but adds robustness)

Testing the Solution

If you save your input to sample.txt and run either command, you'll get exactly the output you're expecting:

File: /Music/David Bowe/1.mp3 Modify: 2010-11-24 09:36:33.000000000 -0200 File: /Music/Music/David Bowe/Tom.mp3 Modify: 2010-10-22 11:12:15.000000000 -0200 File: /Music/Music/David Bowe/Hero.mp3 Modify: 2010-10-26 07:21:56.000000000 -0200 File: /Music/Music/David Bowe/AbsoluteBeginners.mp3 Modify: 2010-10-22 11:12:07.000000000 -0200 File: /Music/Music/David Bowe/ImAfraidOfAmericans.mp3 Modify: 2011-11-13 08:54:57.000000000 -0200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:18:21