如何提取以模式开头的行和两个模式之间的块?

Mar*_*ert 1 sed shell-script

我有infile.tex以下形式的文件(例如,)

AAAA
BBBB AAAA
CCCC BBBB AAAA

%%## Just some text
\begin{example}[foobar]
\begin{Sinput}
> set.seed(271)
> U <- runif(10)
> plot(U, 1-U)
\end{Sinput}
AAAA BBBB CCCC
\begin{Sinput}
> plot(qnorm(cbind(U, 1-U)))
\end{Sinput}
\end{example}
Run Code Online (Sandbox Code Playgroud)

我想提取所有以%%## and开头的行以及\begin{Sinput}and之间的所有行\end{Sinput},所以

%%## Just some text
\begin{Sinput}
> set.seed(271)
> U <- runif(10)
> plot(U, 1-U)
\end{Sinput}
\begin{Sinput}
> plot(qnorm(cbind(U, 1-U)))
\end{Sinput}
Run Code Online (Sandbox Code Playgroud)

我试图与sed

sed -n '/%%##\|\\begin{Sinput}/,/\\end{Sinput}/p' infile.tex # 但也包含 \begin{example}[foobar]

sed -n '/^%%##\|\\begin{Sinput}/,/\\end{Sinput}/p' infile.tex # 但不包含以开头的行 %%##

注意:上面的内容是从这里派生出来的。此外,“两步”解决方案(首先提取以...开头的所有行,然后提取所有块)也可能是可能的(我只是没有看到如何并且似乎sed允许选择多个“模式”,以便看起来更优雅)。

ste*_*eve 5

awk其范围运算符 (,) 对此非常有效。在末尾 (;) 标记一个额外的过滤器,然后嘿嘿。

awk '/^\\begin\{Sinput\}/,/^\\end\{Sinput\}/;/^%%##/' infile.tex
%%## Just some text
\begin{Sinput}
> set.seed(271)
> U <- runif(10)
> plot(U, 1-U)
\end{Sinput}
\begin{Sinput}
> plot(qnorm(cbind(U, 1-U)))
\end{Sinput}
Run Code Online (Sandbox Code Playgroud)