awk打印第一行和最后一行实例

时间:2017-08-16 01:12:23

标签: bash awk

好的,所以我有一些需要帮助的代码

使用AWK扫描文件并提取具有IP地址192.168.122.1

活动的行

打印3行输出

 a) date/time first activity on the IP address was detected

 b) date/time last activity on the IP address was detected

 c) Total number of events detected on the IP address     

1 个答案:

答案 0 :(得分:1)

根据你到目前为止所说的话,这样的事情对你有用:

# find all lines containing the IP
grep -F 192.168.122.1 FILE > tmp   

head -n1 tmp    # print first such line
tail -n1 tmp    # print last such line
wc -l tmp       # count the number of such lines

如果你必须使用awk,这是一种方式:

# invoke as:
#     awk -f this_file.awk FILE

BEGIN {
    count = 0
}

/192\.168\.122\.1/ {
    if (count == 0) {
        print $0   # print the first line containing the IP
        last = $0  # in case the first line also happends to be the last
        count = 1
    } else {
        count += 1  # record that another line contained the IP
        last = $0  # remember this line in case it ends up being the last
    }
}

END {
    if (count > 0) {
        print last  # print the last line containing the IP
    }
    print count
}