Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed to delete a string between parentheses

Tags:

bash

sed

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.

like image 891
Teddy T Avatar asked Jan 10 '23 03:01

Teddy T


2 Answers

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.

like image 152
MightyPork Avatar answered Jan 16 '23 17:01

MightyPork


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.

like image 33
buydadip Avatar answered Jan 16 '23 18:01

buydadip