这很明显 IMO 是我们在脚本中注释每个命令。脚本可以这样写:
#!/usr/bin/awk -f
$1 ~ /#BEGIN/ { # If we match the BEGIN line
a=1 # Set a flag to one
next # skip to the next line
}
a != 0 { # if the flag is not zero
print $0 # print the current line
}
$1 ~ /#END/ { # if we match the END line
exit # exit the process
}
请注意,我将a 扩展为等效形式a!=0{print $0},以使这一点更清楚。
所以脚本在设置标志时开始打印每一行,当它到达 END 行时,它在退出之前已经打印了该行。由于您不希望打印 END 行,因此您应该在打印该行之前退出。所以脚本应该变成:
#!/usr/bin/awk -f
$1 ~ /#BEGIN/ { # If we match the BEGIN line
a=1 # Set a flag to one
next # skip to the next line
}
$1 ~ /#END/ { # if we match the END line
exit # exit the process
}
a != 0 { # if the flag is not zero
print $0 # print the current line
}
在这种情况下,我们在打印行之前退出。简而言之,可以写成:
awk '$1~/#BEGIN/{a=1;next}$1~/#END/{exit}a' file
或者更短一点
awk '$1~/#END/{exit}a;$1~/#BEGIN/{a=1}' file
关于 cmets 中提出的附加约束,为了避免跳过要打印的块中的任何 BEGIN 块,我们应该删除 next 语句,并像上面的示例一样重新排列行。展开后的形式是这样的:
#!/usr/bin/awk -f
$1 ~ /#END/ { # if we match the END line
exit # exit the process
}
a != 0 { # if the flag is not zero
print $0 # print the current line
}
$1 ~ /#BEGIN/ { # If we match the BEGIN line
a=1 # Set a flag to one
}
为了避免在要打印的块之前找到 END 行时退出,我们可以在退出之前检查标志是否设置:
#!/usr/bin/awk -f
$1 ~ /#END/ && a != 0 { # if we match the END line and the flag is set
exit # exit the process
}
a != 0 { # if the flag is not zero
print $0 # print the current line
}
$1 ~ /#BEGIN/ { # If we match the BEGIN line
a=1 # Set a flag to one
}
或以简明形式:
awk '$1~/#END/&&a{exit}a;$1~/#BEGIN/{a=1}' file