博客
关于我
无基础学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/

你可能感兴趣的文章
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>