Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a file listing all the directories on a hard drive. I want to delete all the instances of a line with the word "Directory" followed by two blank lines. That is, I want to delete all three of those lines every time the sequence occurs.

I have already deleted all the lines with "<DIR> .", "<DIR> ..", and "0 Files" -- but there is still some leftover stuff.

The original task was to delete each 6-line sequence with the following pattern:

Directory of m:\Winter Interludes

12/20/2020  10:24 PM    DIR          .
12/20/2010  10:24 PM    DIR          ..
               0 File(s)              0 bytes
share|improve this question

migrated from Apr 9 '11 at 5:08

This question came from our site for professional and enthusiast programmers.

Use regular expressions, and your favorite scripting language/command-line tool :). – Santiago Lezica Apr 9 '11 at 3:11
I can't figure out how to match three lines at a time, before deciding to delete them. – Steve Stoddard Apr 9 '11 at 3:19
Also, I haven't yet figured out how to format the original question so that those last three lines don't come out on the same line . . . – Steve Stoddard Apr 9 '11 at 3:20
Hey, thanks for editing that question. I still haven't got anything to work, but I haven't given up. – user75683 Apr 9 '11 at 6:35


slurp whole file into array

Loop over array index

if no flags are set and the first match appears, set a flag

if flag, and second line matches, set another flag

if both flag, and third line matches then delete the three lines from the array

End Loop

Print modified array back out

should also work in python


If you want to use a single regexp to match across multiple lines, perl has a post-regex flag "m" for that. From perlre:

m Treat string as multiple lines. That is, change ^'' and$'' from matching at only the very start or end of the string to the start or end of any line anywhere within the string,

s Treat string as single line. That is, change .'' to match any character whatsoever, even a newline, which it normally would not match. The /s and /m modifiers both override the $* setting. That is, no matter what $* contains, /s without /m will force ^'' to match only at the beginning of the string and $'' to match only at the end (or just before a newline at the end) of the string. Together, as /ms, they let the.'' match any character whatsoever, while yet allowing ^'' and$'' to match, respectively, just after and just before newlines within the string.

share|improve this answer
perl -0777 -p -e 's/[^\n]*Directory[^\n]*\n\n\n//sg' input
share|improve this answer

In vim, you could use: :%s:Directory{ctrl+v, return}{ctrl+v}return:

share|improve this answer

You must log in to answer this question.