2011-09-11 48 views
5

我需要刪除一條匹配線和一條匹配線。 e.g在文件下我需要刪除線1 & 2.如何刪除匹配的行和上一行?

我試過的 「grep -v -B 1」 的頁面。 「的1.txt ,我估計它不打印matchning線和背景。

我試過How do I delete a matching line, the line above and the one below it, using sed?但不明白sed的用法。

---1.txt-- 
**document 1**       -> 1 
**page 1 of 2**      -> 2 

testoing 
testing 

super crap blah 

**document 1** 
**page 2 of 2** 
+2

嘗試['tac file | sed -e'/ foo /,+ 1d'| tac'](http://stackoverflow.com/a/31227307/2297751) – Jon

回答

1

不太熟悉SED,但這裏有一個Perl的表達這樣的伎倆:

cat FILE | perl -e '@a = <STDIN>; 
        for($i=0 ; $i <= $#a ; $i++) { 
        if($i > 0 && $a[$i] =~ /xxxx/) { 
         $a[$i] = ""; 
         $a[$i-1] = ""; 
        } 
        } print @a;' 

編輯:

其中 「xxxx」 是什麼你正在嘗試匹配。

+0

這必須首先緩衝整個文件... –

+0

而貓的無用的用途應該去。 – tripleee

+0

是的,這個解決方案的某些部分可以被批評,但是一般概念是可靠的,示例代碼很好地實現了它。這很容易理解。足以讓某人開始。這就是答案的重點。它不需要是完美的。 我喜歡這個回答。它確實幫助我解決了與原始問題類似的問題。 – Keve

11

你想要做的非常相似answer given

sed -n ' 
/page . of ./ { #when pattern matches 
n #read the next line into the pattern space 
x #exchange the pattern and hold space 
d #skip the current contents of the pattern space (previous line) 
} 

x #for each line, exchange the pattern and hold space 
1d #skip the first line 
p #and print the contents of pattern space (previous line) 

$ { #on the last line 
x #exchange pattern and hold, pattern now contains last line read 
p #and print that 
}' 

而作爲一個單行

sed -n '/page . of ./{n;x;d;};x;1d;p;${x;p;}' 1.txt 
+0

請注意,你可以在一行上做:'sed -n'/ page 1/{n; x; d;}; x; 1d; $ G; p'1.txt' – Beta

+0

@Beta:當然,多餘的線條等僅僅是註釋 – Hasturkun

+1

爲什麼這是低調的?它執行問題提問者所需的內容(並且在sed中啓動) – Hasturkun

2

grep -v -B1行不通的,因爲它會跳過這些行,但將包括他們後來的東西(由於到-B1。要檢查這一點,請嘗試以下命令:

**document 1**       -> 1 
**page 1 of 2**      -> 2 

**document 1** 
**page 2 of 2** 
**page 3 of 2** 

您會注意到page 2行將被忽略,因爲該行不匹配,而下一行不匹配。

有一個簡單的解決方案AWK:

awk '!/page.*of.*/ { if (m) print buf; buf=$0; m=1} /page.*of.*/ {m=0}' 1.txt 

awk命令說以下內容:

如果當前行有一個「頁面的......」,那麼它將表明你的天堂」 t找到了一個有效的行。如果您沒有找到該字符串,則打印上一行(存儲在buf中)並將緩衝區重置爲當前行(因此強制其延遲1)

1
grep -vf <(grep -B1 "page.*of" file | sed '/^--$/d') file 
+0

您想要將'-x'選項添加到外部'grep'。這不是非常有效。 – tripleee