0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

awkで複雑な条件のテキスト抽出をする

Last updated at Posted at 2023-04-18

やりたいこと

次のようなテキストから目的の行だけを取り出したい

input.txt
other-line 
second-pattern
second-pattern
first-pattern     <--- 1.first-pattern が最初に現れて
other-line
other-line
other-line
second-pattern    <---- 2.次の最初の second-patternが現れてから
target-line1            *目的の行
target-line2            *目的の行
target-line3            *目的の行
end-pattern       <--- 3.end-pattern が現れるまでの行
other-line
first-pattern
other-line
first-pattern

コマンドと結果の例

1.目的の行だけを取り出す場合
awk "\!f&&/first-pattern/{f=1} f==2&&/end-pattern/{exit} f==2{print} f==1&&/second-pattern/{f=2}"  input.txt
target-line1            *目的の行
target-line2            *目的の行
target-line3            *目的の行
2.目的の行とsecond-pattern,end-patternの行を含める場合
awk "\!f&&/first-pattern/{f=1} f==1&&/second-pattern/{f=2} f==2{print} f==2&&/end-pattern/{exit}"  input.txt
second-pattern    <---- 2.次の最初の second-patternが現れてから
target-line1            *目的の行
target-line2            *目的の行
target-line3            *目的の行
end-pattern       <--- 3.end-pattern が現れるまでの行

意味

  • fを状態変数として使い、f==2のときに出力している
  • !f&&/first-pattern/{f=1}
    変数fが0、かつ、「first-pattern」が出現したら、変数fに1を代入(あらゆる変数の初期値は全て0)
  • f==2&&/end-pattern/{exit}
    変数fが2、かつ、「end-pattern」が出現したら、終了
  • f==2{print}
    変数fが2の場合、その行を出力
  • f==1&&/second-pattern/{f=2}
    変数fが1、かつ、「second-pattern」が出現したら、変数fに2を代入

検証環境

% sw_vers
ProductName:	macOS
ProductVersion:	12.6.3
BuildVersion:	21G419

% awk --version
awk version 20200816
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?