単一条件を使用して複数行を出力するには?

単一条件を使用して複数行を出力するには?

次のパターンを含むファイルがあります。

n0 n1 n2 ... ni
-------------------------------
N0 N1
<empty line>

N0が特定の数値より小さい場合は、次のようにします。

  • N1ライン上2ライン
  • N1ライン
  • N1ラインの下の空のライン

出力に表示されます。これを行うにはどうすればよいですかawk?または他のユーティリティを使用できますか?

ベストアンサー1

「翼」を使う

これにより、N0行が印刷されます。 < LIMIT:

# -v sets variables which can be used inside the awk script

awk -v LIMIT=10 '

    # We initialize two variables which hold the two previous lines
    # For readability purposes; not strictly necessary in this example
    BEGIN {
        line2 = line1 = ""
    }

    # Execute the following block if the current line contains
    # two fields (NF = number of fields) and the first field ($1)
    # is smaller than LIMIT

    ($1 < LIMIT) && (NF == 2) {
        # Print the previous lines saved in line2 and line1,
        # the current line ($0) and an empty line.
        # RS, awk's "record separator", is a newline by default

        print line2 RS line1 RS $0 RS
    } 

    # For all other lines, just keep track of previous line (line1),
    # and line before that (line2). line1 is saved to line2, and the
    # current line is saved to line1

    { line2 = line1; line1 = $0 }
' file

おすすめ記事