如何保留每个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 theFile:lineb: 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 aModify:line for thisFile:), swap back and delete the current line- If the hold space is empty (first
Modify:line for thisFile:), 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, setkeep_modifyto 1 (we want to keep the nextModify:line), then move to the next line - When a
Modify:line is found: ifkeep_modifyis 1, print the line and setkeep_modifyto 0 (so subsequentModify:lines are skipped); otherwise, skip the line - The final
1ensures 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
相关产品推荐
相关产品推荐

