Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete a string inside parentheses using sed, inside a sed script?

Tags:

bash

sed

ubuntu

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.

like image 386
Joshua Borden Avatar asked Jul 19 '26 22:07

Joshua Borden


1 Answers

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:

enter image description here

like image 127
Wiktor Stribiżew Avatar answered Jul 22 '26 11:07

Wiktor Stribiżew