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
How to remove square brackets and any text inside?
提问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'

