如何使用 grep 打印行直到匹配右括号?

如何使用 grep 打印行直到匹配右括号?

我有一个包含如下代码的文档:

Some words.

\NOTETAKING{ some text
 This is some {} text.
  This is more text \this{}.
}

Some more words.

如何使用 grep 匹配以 \NOTETAKING{ 开头的行,以及该括号内的所有文本,直到并包括匹配的右括号的行?

  • NOTETAKING 可以在文档中出现多次,我需要找到第 n 次出现,例如有时搜索第 1 次出现,有时搜索第 3 次出现。
  • 它总是出现在行首。
  • 其结束括号始终单独占据一行。

答案1

如果您选择 Perl,这里有一种方法可以完成这项工作。

我假设}定义块结束的是在一行的开头,如果在之前可以有一些空格},则使用/^\h*}/而不是/^}/

代码:

perl -ane 'if(/\\NOTETAKING/ ... /^}/){$counter++ if /\\NOTETAKING/; print if $counter==2}' file.txt

输入文件:

Some words.

\NOTETAKING{ some text 1rst occurrence
 This is some {} text.
  This is more text \this{}.
}

Some more words.
Some words.

\NOTETAKING{ some text 2nd occurrence
 This is some {} text.
  This is more text \this{}.
}

Some more words.
Some words.

\NOTETAKING{ some text 3rd occurrence
 This is some {} text.
  This is more text \this{}.
}

Some more words.

输出:

\NOTETAKING{ some text 2nd occurrence
 This is some {} text.
  This is more text \this{}.
}

解释:

perl -ane '                         # invoke Perl
if(/\\NOTETAKING/ ... /^}/){            # if we are between \NOTETAKING  & } at the beginning of line
    $counter++ if /\\NOTETAKING/;           # increment $counter if the line contains \NOTETAKING
    print if $counter==2                    # print current line, here for the 2nd occurrence, change the "2" with the occurrenec number you want to be printed
}                                       # endif
'                                   # end perl code
file.txt                            # input file

相关内容