teamg
teamg

Reputation: 723

How to use sed to remove parenthesis but not all of them

I have a file full of lines like the one below:

("012345", "File City (Spur)  NE", "10.10.10.00", "b.file.file.cluster1")

I'd like to remove the parentheses around Spur but not the beginning and ending (). I can do this and it works but looking for one simple sed command.

 sed -i 's/) //g' myfile.txt
 sed -i 's/ (//g' myfile.txt

Not sure if it's possible but would appreciate any help.

Upvotes: 1

Views: 166

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

If you want to remove all ( after a space, and ) before a space, you can use

sed -i 's/) / /g;s/ (/ /g' myfile.txt

See the online demo:

s='("012345", "File City (Spur)  NE", "10.10.10.00", "b.file.file.cluster1")'
sed 's/) / /g;s/ (/ /g' <<< "$s"
# => ("012345", "File City Spur  NE", "10.10.10.00", "b.file.file.cluster1")

Note that in POSIX BRE, unescaped ( and ) chars in the regex pattern match the literal parentheses.

A more precise solution can be written with Perl:

perl -i -pe 's/(^\(|\)$)|[()]/$1/g' myfile.txt

See an online demo. Here, ( at the start and ) at the end are captured into Group 1 (see (^\(|\)$)) and then [()] matches any ( and ) in other contexts, and replacing the matches with the backreference to Group 1 value restores the parentheses at the start and end only.

Upvotes: 1

sseLtaH
sseLtaH

Reputation: 11217

Using sed grouping and back referencing

sed -Ei 's/(\([^(]*).([^\)]*).(.*)/\1\2\3/' input_file`
("012345", "File City Spur  NE", "10.10.10.00", "b.file.file.cluster1")

This will match the entire line excluding the inner parenthesis represented as . not within the grouped parenthesis

Upvotes: 0

Related Questions