После сценария Perl я использую для маркировки первых несогласованных круглых скобок:
#!/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
Использование:
$ 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