有人可以帮助了解如何解释/阅读此awk命令吗?
awk '/foo/{if (a ~ /abc/) print a; print} {a=$0}' file
对于包含以下行的文件:
abc 0
def
abc 1
foo 1
ghi
jkl
foo 2
foo 3
mno
abc 2
foo 4
foo 5`
观察到该命令将输出打印为:
abc 1
foo 1
foo 2
foo 3
abc 2
foo 4
foo 5`
答案 0 :(得分:3)
有人可以帮助了解如何解释/阅读此awk 命令?
awk '/foo/{if (a ~ /abc/) print a; print} {a=$0}' file
简而言之,上面的命令是什么,它搜索包含foo
的行,如果找到了行,那么它会检查先前的读取行(variable a
)是否有abc
,如果为真然后,它打印上一行(that is variable a contents; print a)
,然后打印当前行(line which contains "foo"; print
)。
说明如下:
awk ' # call awk
/foo/{ # if line/record/row contains "foo" then
if (a ~ /abc/) # if variable a contains "abc" then
print a; # print contents of variable a
print # print current record/row/line
}
{
a=$0 # save current record/line/row in variable a
}
' file # here you read file