2013-07-08 90 views
2

我有一個包含方括號裏面的一些文本文件,如:如何刪除方括號和裏面的任何文本?

The fish [ate] the bird. 
[This is some] text. 
Here is a number [1001] and another [1201]. 

我需要刪除所有的包含在廣場Brack的內部信息和brakets,如:

The fish the bird. 
text. 
Here is a number and another . 
  • 我試過sed -r 's/\[[+]\]//g' file.txt,但這沒有奏效。

如何刪除模式[<anything>]中的任何內容?

回答

9

試試這個sed的行:

sed 's/\[[^]]*\]//g' 

例如:

kent$ echo "The fish [ate] the bird. 
[This is some] text. 
Here is a number [1001] and another [1201]."|sed 's/\[[^]]*\]//g' 
The fish the bird. 
text. 
Here is a number and another . 

解釋:

的正則表達式實際上是直截了當:

\[  #match [ 
[^]]* #match any non "]" chars 
\]  #match ] 

所以它是

匹配串,從[然後所有字符但]並用]

+0

它的工作原理。你能解釋一下它的工作原理嗎? – Antarus

+1

@Antarus請參閱編輯回答 – Kent

+0

肯特。 thnx爲exp。 :) – Antarus

-1

結束的sed的/([^])*)/ 替換文本/G'在括號()的情況下