首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >awk打印实例的第一行和最后一行

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

Stack Overflow用户
提问于 2017-08-16 09:12:23
回答 1查看 1K关注 0票数 0

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

使用AWK扫描文件并提取IP地址192.168.122.1的活动行

打印出3行输出

代码语言:javascript
运行
复制
 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     
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-16 09:18:41

根据你到目前为止所说的,这样的东西可能对你有用:

代码语言:javascript
运行
复制
# 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,这里有一种方法:

代码语言:javascript
运行
复制
# 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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45703664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档