博客
关于我
无基础学Linux(11)——grep、awk、sed
阅读量:657 次
发布时间:2019-03-15

本文共 1134 字,大约阅读时间需要 3 分钟。

Linux三剑客

一、grep

grep是一种强大的文本搜索工具。它可以使用特定模式匹配文本,并默认输出匹配的行。grep是文件中查找符合条件字符串的利器,常用于信息筛选。在使用grep时,需要注意模式匹配的规则,比如使用^$表示空行,wtmp表示匹配包含ttyp的用户信息等。

常见用法:

1. 带输出内容:`grep pattern file.log`2. 筛选非空行:`grep -v "^$" file.log`3. 结合搜索关键字:`grep -v "wtmp" file.log`4. 排序并取定数量:`grep pattern file.log | head -3`

二、awk

awk是一款功能强大的文本处理工具,非常适合处理数据分析和表格操作。在实际使用中,awk脚本可以包含复杂的逻辑判断和变量操作。以下是awk的基本使用 syntax:

awk [options] { before | condition | action }

示例:

1. 打印[start]并输出每一行内容:```bashawk 'BEGIN {printf("%s\n","start")} {print}' file.log```2. 只显示时间信息:```bashawk '{print $3}' time.log```3. 找出使用时长超过3分钟的记录:```bashawk -v end=3'{ if ($3 > end) print $1"-"$2 }' time.log```4. 处理多个文件并汇总结果:```bashawk 'FNR==1{print}; {a[$1]++}' *.log | sort```

三、sed

sed是一种简单但强大的文本处理工具,与awk的功能有所不同。它主要用于简单的字符串替换和行操作。

常见用法:

1. 全局替换:`sed -i "s/abc/123/g" file.log` 或 `sed "s/abc/123/g" file.log`2. 删除第一、二行:`sed "1,2d" file.log`3. 查找并删掉含有"added"的行:`sed "/added/d" file.log`4. 向文件中添加新内容:`sed -i "s/^/新内容/abetwee` file.log5. 处理末尾或首位字符:```bashsed "1q" file.log # 只显示第一行sed "2q" file.log # 删除第一行并显示第二行以下内容```

如果需要在vim中完成类似操作,可以使用以下命令:

```bashvim -c "move Till mise"```

希望这些工具能帮助你更高效地处理文本文件!

转载地址:http://nxdmz.baihongyu.com/

你可能感兴趣的文章
Program type already present: android.support.v4.widget.EdgeEffectCompat
查看>>
PyTorch中文版官方教程来啦(附下载)
查看>>
Progress Kemp LoadMaster 远程命令执行漏洞复现(CVE-2024-1212)
查看>>
Project configuration is not up-to-date with pom.xml. Run Maven->Update Project
查看>>
Project Euler 15 Lattice paths
查看>>
Project Euler 48 Self powers( 大数求余 )
查看>>
Project Euler Problem 12: Highly divisible triangular number
查看>>
ProjectEuler 2
查看>>
projection介绍及EPSG:4326和EPSG:3857的投射转换
查看>>
project打开文件时,显示无法识别此文件格式?
查看>>
Prometheus + Grafana on Kubernetes部署
查看>>
prometheus + grafana进行服务器资源监控
查看>>
Prometheus Alertmanager 告警配置详解
查看>>
Prometheus Grafana 展示平台
查看>>
Prometheus pushgateway使用详解
查看>>
Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
查看>>
Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
查看>>
Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
查看>>
Prometheus 云原生 - 监控 Linux、MySQL、Redis、RabbitMQ、Docker、SpringBoot 3.x
查看>>
Prometheus 介绍
查看>>