bash 使用sed删除括号之间的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27825977/
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
Using sed to delete a string between parentheses
提问by Teddy T
I'm having trouble figuring how to delete a string in between parentheses only when it is in parentheses. For example, I want to delete the string "(Laughter)", but only when it's in parenthesis and not just make it a case sensitive deletion since a sentence within that string starts with Laughter.
我无法确定如何仅在括号中删除括号之间的字符串。例如,我想删除字符串“(Laughter)”,但仅当它在括号中时,而不是仅仅将其设为区分大小写的删除,因为该字符串中的句子以 Laughter 开头。
回答by MightyPork
I'm not sure I understand you correctly, but the following will remove text between parentheses:
我不确定我是否理解正确,但以下内容将删除括号之间的文本:
sed "s/[(][^)]*[)]/()/g" myfile
(or as Llama pointed out in comments, just:)
(或者正如 Llama 在评论中指出的那样,只是:)
sed "s/([^)]*)/()/g" myfile
It matches a literal open paren [(]
followed by any number of non-)
characters [^)]*
followed by a literal close paren [)]
.
它匹配文字打开括号,[(]
后跟任意数量的非)
字符,[^)]*
然后是文字关闭括号[)]
。
Example:
例子:
$ echo "Blah blah (potato) moo (cow is a pretty bird)(hello)" | sed "s/[(][^)]*[)]/()/g"
Blah blah () moo ()()
Use //
instead of /()/
there if you don't want the empty parens in the output.
如果您不想在输出中使用空括号,请使用//
而不是/()/
那里。
回答by buydadip
Here's an awk
solution because, why not?
这是一个awk
解决方案,因为,为什么不呢?
awk '{gsub("[(][^)]*[)]","")}1' file
OR
或者
awk -F '[(][^)]*[)]' '{for(i=1; i<=NF; i+=1)printf("%s",$i);printf("\n")}' file
Remember that in order to escape parentheses use must enclose them in []
brackets.
请记住,为了转义括号,必须使用括号将它们括起来[]
。
By using [^)]*
, as @MightyPork did in his answer, which indicates any number of characters that are not parentheses, will reduce the greed of the match. In contrast, using .*
instead, would result in a greedy match.
通过使用[^)]*
,正如@MightyPork 在他的回答中所做的那样,表示任意数量的非括号字符,将减少匹配的贪婪。相反,使用.*
相反,会导致贪婪匹配。