Using sed to delete a string between parentheses

我们两清 提交于 2020-03-13 06:45:10

问题


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.


回答1:


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:)

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.




回答2:


Here's an awk solution because, why not?

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.



来源:https://stackoverflow.com/questions/27825977/using-sed-to-delete-a-string-between-parentheses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!