bash 如何删除方括号和里面的任何文字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17522855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:51:11  来源:igfitidea点击:

How to remove square brackets and any text inside?

bashsed

提问by Village

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.
  • 我试过了sed -r 's/\[[+]\]//g' file.txt,但这没有用。

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

如何删除模式中的任何内容[<anything>]

回答by Kent

try this sed line:

试试这个 sed 行:

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 ]

匹配字符串,以[所有字符开头,但]]

回答by Amitanshu Gupta

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

sed 's/([^])*)/在括号 () 的情况下替换文本/g'