Issue
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.
Solution
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.
Answered By - Wiktor Stribiżew Answer Checked By - Mary Flores (WPSolving Volunteer)