角かっこを含むテキストの抽出

角かっこを含むテキストの抽出

次のテキストがあります。

Sentence #1 (n tokens):
Blah Blah Blah
[...
 ...
 ...]
( #start first set here
 ... (other possible parens and text here)
 ) #end first set here

(...)
(...)

Sentence #2 (n tokens):

2番目の角かっこセット(それらの間のすべての項目を含む)を抽出したいと思います。つまり、

(
 ... (other possible parens here)
)

これを行うbashメソッドはありますか?簡単にしてみました

 's/(\(.*\))/\1/'

ベストアンサー1

それはすべてです。より良い方法があるかもしれませんが、私の考えでは、次の方法が最初に浮かびます。

echo 'Sentence #1 (n tokens):
Blah Blah Blah
[...
 ...
 ...]
(
 ... (other possible parens here)
 )

(...)
(...)

Sentence #2 (n tokens):
' | perl -0777 -nE '
    $wanted = 2; 
    $level = 0; 
    $text = ""; 
    for $char (split //) {
        $level++ if $char eq "(";
        $text .= $char if $level > 0;
        if ($char eq ")") {
            if (--$level == 0) {
                if (++$n == $wanted) { 
                    say $text;
                    exit;
                }
                $text="";
            }
        }
    }
'

出力

(
 ... (other possible parens here)
 )

おすすめ記事