如何使用单个条件输出多行?

如何使用单个条件输出多行?

我有一个包含以下模式的文件:

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

如果 N0 小于特定数字,我想要:

  • N1 线上方 2 行
  • N1线
  • N1 行下方的空行

出现在输出中。我如何使用awk或任何其他实用程序来执行此操作?

答案1

使用“awk”

这将打印 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

相关内容