2つのパターン間の開始と終了の印刷(範囲の終わりを除く)

2つのパターン間の開始と終了の印刷(範囲の終わりを除く)

sed -n "/START PATTERN/,/END PATTERN/p" file.txtパターンを使用してファイルを検索したいです。

file.txt内容は

~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~3.~ ~output~.
~keyword blablabla~, ~not the output~.
~1.~ ~not the output~.
~2.~ ~not the output~.
~keyword blablabla2~, ~not the output~.
~1.~ ~not the output~.
~2.~ ~not the output~.
~3.~ ~not the output~.
~4.~ ~not the output~.
~blablabla~, ~not the output~.
~1.~ ~not the output~.
~2.~ ~not the output~.
~3.~ ~not the output~.
~4.~ ~not the output~.

私の予想結果は

~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~keyword~, ~output~.
~1.~ ~output~.
~2.~ ~output~.
~3.~ ~output~.

したがって、開始パターンはkeyword中央にあり、その後~に文字が.続きます。/~keyword~./

終了パターン~の後にはアルファベット文字が続き、次にcharが続きます.

私が実行すると、sed -n "/~keyword~./,/[~][[:alpha:]]./p" file.txt出力は次のようになります。

~keyword~, ~output~.
~1.~ ~output~.
~keyword~, ~output~.
~1.~ ~output~.

2行目と3行目は出力に印刷されないので、私の質問は私のアプローチにどのような問題がありますか?提供されたソリューションを使用してインスピレーションを得ました。ここ

私もsed "/~keyword~./,/[~][[:alpha:]]./!d;//d" file.txt空の出力を取得しようとしました(この質問からインスピレーションを受けて)

この質問は、正規表現にsedを使用することについて具体的に質問したため、重複としてマークされた質問とは異なります。これを念頭に置いて重複と思われる場合は重複として表示してください。

ベストアンサー1

sedこのツールが仕事に適しているか見てみましょう。

sed '/^~[[:alpha:]].*/!{               # if line doesn't match this pattern
H                                      # append it to hold space
$!d                                    # and delete it if it's not the last line
b end                                  # else branch to label end
}
//b end                                # if line matches, branch to label end
: end                                  # label end
x                                      # exchange pattern space w. hold space
/^~keyword~.*/p                        # if pattern space matches, print it
d' infile                              # delete pattern space

gnu sed1行で書くことができます。

sed '/^~[[:alpha:]].*/!{H;$!d;b end};//b end;: end;x;/^~keyword~.*/p;d' infile

おすすめ記事