4

Given a line like this: "hello my (name) is (user), how can I remove all '()' using sed?

What I'm currently doing is highlighting the line using visual block, and then :s/(//g and again for ). Is there a way to remove both (, ) in one sed command?

My end goal is "hello my name is user"

2
  • 3
    Is the goal to remove all parentheses, or only matched pairs of them? For example, if a line had a ( but no corresponding ), what should happen? Or what if it has a closing parenthesis before the opening one, like )(?
    – David Z
    Commented Feb 11, 2019 at 19:51
  • I use this on a very limited controlled input, where the only parentheses are paired Commented Feb 12, 2019 at 6:52

3 Answers 3

13

You can use tr -d '()' <infile too.

0
13

You can use character class [()] as Regex pattern, and replace the pattern with empty string to remove them:

sed 's/[()]//g'

So:

% sed 's/[()]//g' <<<"hello my (name) is (user)"
hello my name is user

g modifier does the operation on all matches, otherwise sed will stop after the first match.

4

You can save the bracket content in a group and replace by that:

sed 's/(\([^)]*\))/\1/g'

This saves everything inside the brackets ([^)]* simply matches everything except )) in group 1 and replaces the whole bracket by it. Doing that globally means to do it for every pair of brackets in the line.

Usage example

$ echo '"hello my (name) is (user)"' | sed 's/(\([^)]*\))/\1/g'
"hello my name is user"
3
  • 2
    Why capture a group if all you want is to remove a character? Even if you don't want to use a character class, you could simply do sed 's/(//g; s/)//g' More importantly, this fails on input like ((hello) or (foo or (a((b())d)).
    – terdon
    Commented Feb 11, 2019 at 12:57
  • @terdon Just removing characters fails on something like ((test), but OP asks how to remove enclosing brackets!
    – dessert
    Commented Feb 11, 2019 at 13:04
  • 3
    Even if you only limit to that, it still fails on ` (a (foo) ab)`.
    – terdon
    Commented Feb 11, 2019 at 13:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .