How to remove square brackets and any text inside?

2020-07-24 06:09发布

I have a document containing some text inside square brackets, e.g.:

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

I need to delete all of the information contained inside the square brack and the brakets, e.g.:

The fish  the bird.
 text.
Here is a number  and another .
  • I tried sed -r 's/\[[+]\]//g' file.txt, but this did not work.

How can I delete anything in the pattern [<anything>]?

标签: bash sed
2条回答
太酷不给撩
2楼-- · 2020-07-24 06:11

try this sed line:

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

example:

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 .

explanation:

the regex is actually straightforward:

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

so it is

match string, starting with [ then all chars but ] and ending with ]

查看更多
We Are One
3楼-- · 2020-07-24 06:14

sed 's/([^])*)/replacement text/g' in case of Parenthesis ()

查看更多
登录 后发表回答