3

I would like to find out, if, in my file, there is a right number of brackets. I can make my file look like

(((()))()(())) ((()))()

How can I use sed to compute those brackets and print yes or no instead of the line, if the number of brackets is right or not?

  • Just to be clear... the brackets do not extend beyond the line? – mikeserv Apr 7 '15 at 9:22
  • Yes, each line should have its own brackets right, no brackets over the line should be counted for this line. – PObdr Apr 7 '15 at 9:23
  • Can there be other characters inside the brackets? – terdon Apr 7 '15 at 11:07
  • I managed to clear any other characters so on the line, there are only "(" and ")". – PObdr Apr 7 '15 at 11:27
2

Just for test purpose

sed ':1;s/([^()]*)//g;t1;s/.*[()].*/No/;t;s/.*/Yes/'

prints "Yes" for correct number and "No" for opposite for each line.

3
sed '  s/.*/YES(&)/;:t
       s/([^()]*)//g;tt
       s/.....*/NO/'
2

Simple Perl solution:

perl -ne '1 while s/\(\)//g; print /[()]/ ? "Invalid\n" : "OK\n"' input.txt

Explanation: the while loop removes () until it's no longer possible. If there are any parentheses left, they were not balanced.

0

The following is doing a more complex job: marking the first un-matched parentheses:

#!/usr/bin/perl
use strict;
undef $/;
$_= <>;                   # slurp input
my $P = qr{[^()]*};       # $P = not parentheses

                          # repace matched parentheses by marks
while(s!       \( ($P) \)        !\cA$1\cB!gx){}
while(s!^ ($P) \( (.*) \) ($P) $ !$1\cB$2\cB$3!sgx){}

s!([()])! → $1!;          # mark the first unmatched ()
y!\cA\cB!()!;             # replace marks

print

Usage:

$ cat f
1(2(3(4(5)6)7)8(9)10(
   11(12)13)14)  (15 ( and ) 
      (16(17(18)19)
   20)21(22)23
$ parentesis f
1(2(3(4(5)6)7)8(9)10(
   11(12)13)14)   → (15 ( and ) 
      (16(17(18)19)
   20)21(22)23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.