问题
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