I would like to remove text inside parentheses (including the parentheses) using sed in a sed script. For example, I would like to delete the phrase (Chris Pratt) and (Chris-Pratt) and keep (Chris_Pratt). (They are both on the same line). And do this for the entire file. For example, the line looks like this:
Star Lord (Chris Pratt), (Chris-Pratt), age 42, actor, (Chris_Pratt)
This is what I would want to to look like after the sed command in a sed script:
Star Lord, age 42, actor, (Chris_Pratt)
That's what I want to do with every single line (there are multiple lines with other names).
I have already tried:
s/[(][^)]*[)]//g
This one works, but it also deletes the parentheses including the underscore, also:
s/\([[:alpha:]]{1,} [[:alpha:] ]{1,}\)\ //g
This one does work when I run it with sed normally in the command line, but it doesn't work when I run it in a script for some reason.
You can use
sed 's/ *([^()_]*)//g' file > outputfile
Same pattern with POSIX ERE syntax:
sed -E 's/ *\([^()_]*\)//g' file > outputfile
Details:
*( - a literal ( char (since it is a POSIX BRE pattern), when using POSIX ERE, \( must be used[^()_]* - zero or more chars other than (, ) and _) - a literal ) char (since it is a POSIX BRE pattern), when using POSIX ERE, \) must be used.See the online demo:
#!/bin/bash
s='Star Lord (Chris Pratt), age 42, actor, (Chris_Pratt)'
sed 's/ *([^()_]*)//g' <<< "$s"
# => Star Lord, age 42, actor, (Chris_Pratt)
sed -E 's/ *\([^()_]*\)//g' <<< "$s"
# => Star Lord, age 42, actor, (Chris_Pratt)
Demo screenshot:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With