入力ファイルの一部を抽出するawkスクリプト

入力ファイルの一部を抽出するawkスクリプト

awk「start」の入力ファイルを検索し、「next」を含む行を見つけて、次の行を表示するスクリプトを作成するにはどうすればよいですか?このような:

    [user]$ cat test.txt
    start
    next
    This line should print
    Ignore this


    [user]$ display.awk test.txt
    This line should print

    [user]$ cat test1.txt
    Ignore this
    next
    Ignore this
    start
    Ignore this
    next
    This line should print
    Ignore this
    next
    Too late so ignore this too
    start
    Ignore this too

    [user]$ display.awk test1.txt
    This line should print

ベストアンサー1

これは文章です:

awk 'BEGIN {start="no"; nextline="no"}; nextline=="yes" {print; exit}; (start=="yes" && /^next$/) {nextline="yes"}; /^start$/ {start="yes"}' test.txt 

スタンドアロンスクリプトで:

#!/bin/awk -f

BEGIN {start="no"; nextline="no"}
nextline=="yes" {print; exit}
(start=="yes" && /^next$/) {nextline="yes"}
/^start$/ {start="yes"}

説明する

最初のポイントを最初に読んだ後、残りのポイントを逆に読み取る方が合理的です。

  • BEGIN {start="no"; nextline="no"}:まず、2つの変数を次に設定します"no"(つまり、まだ見つかりませんでした)。 NBはnext予約語なので使用しましたnextline
  • nextline=="yes" {print; exit}next:前の行で見つかった場合は、その行を印刷して終了します。
  • (start=="yes" && /^next$/) {nextline="yes"}:発見後の行でも検索すると次に設定さstartれます。nextnextline"yes"
  • /^start$/ {start="yes"}:開始が見つかったらstartに設定します"yes"

おすすめ記事