Home > Enterprise >  How to use sed to remove parenthesis but not all of them
How to use sed to remove parenthesis but not all of them

Time:10-19

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.

CodePudding user response:

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.

CodePudding user response:

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

  • Related