How to Remove Strings between two Parenthesis in Unix

sed

I have a requirement like i have to remove the strings or numbers between two Parenthesis in a file. I used sed command but it is working on a single line. My opening Parenthesis is in one line and the closing parenthesis is in other line. How can i do it?

I tried this command using sed:

sed -e 's/([^()]*)//g'

but this works only when My opening and closing parenthesis are on the same line.

For Example:-

Input file:

select a
,b
,c
FROM ABCD
(select e
,f
,g
,h FROM XYZ)

Output should be:

select a
,b
,c
FROM ABCD

Best Answer

Use the following simple perl script to remove every pair of parentheses and their content, even across multiple lines:

#!/usr/bin/perl
undef $/;
$text = <>;
#Flags: g=match repeatedly; s=dot matches newline
$text =~ s/\(.*?\)//gs;
print $text;

If you want to fit it into the commandline, here's the one-liner version:

perl -p0777e 's/\(.*?\)//gs' [filename]

Note that it's shorter and simpler than the perl solutions. -0777 disables the line separator (see the -0 flag under man perlrun), causing the whole file to be processed in one step. Good old perl... It's also (unusually for perl :-)) more readable than messing with sed's pattern space.

Related Question