
我有一個文件列出了硬碟上的所有目錄。我想刪除包含“Directory”一詞的行的所有實例,後面跟著兩個空白行。也就是說,我想在每次序列發生時刪除所有這三行。
我已經刪除了所有帶有"<DIR> ."
、"<DIR> .."
、 和"0 Files"
-- 的行,但仍然有一些剩餘的東西。
最初的任務是刪除具有以下模式的每個 6 行序列:
Directory of m:\Winter Interludes
12/20/2020 10:24 PM DIR .
12/20/2010 10:24 PM DIR ..
0 File(s) 0 bytes
答案1
珀爾:
將整個文件放入數組中
循環數組索引
如果沒有設定標誌並且出現第一個符合項,則設定一個標誌
如果標誌和第二行匹配,則設定另一個標誌
如果標誌和第三行都匹配,則從數組中刪除這三行
結束循環
列印修改後的數組
也應該在 python 中工作
--
如果你想要使用單一正規表示式來符合多行,perl 有一個正規表示式後標誌「m」。來自佩爾雷:
m 將字串視為多行。也就是說,將
^'' and
$'' 從僅匹配字串的開頭或結尾更改為字串中任何位置的任何行的開頭或結尾,s 將字串視為單行。也就是說,將
.'' 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 end (or just before a newline at the end) of the string. Together, as /ms, they let the
.'' 匹配任何字符,同時允許^'' and
$'' 分別匹配字符串中換行符之後和之前的位置。
答案2
perl -0777 -p -e 's/[^\n]*目錄[^\n]*\n\n\n//sg'輸入
答案3
在 vim 中,你可以使用:
:%s:Directory{ctrl+v, return}{ctrl+v}return: