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

你可能感兴趣的文章
php csv 导出
查看>>
php curl 实例+详解
查看>>
php curl_init函数用法(http://blog.sina.com.cn/s/blog_640738130100tsig.html)
查看>>
php curl_multi批量发送http请求
查看>>
php curl请求微信发红包接口出现错误:Peer's Certificate issuer is not recognized.
查看>>
PHP curl请求错误汇总和解决方案
查看>>
php declare(ticks=1)
查看>>
UVA 10474
查看>>
php echo 输出 锘?... 乱码问题
查看>>
PHP empty、isset、isnull的区别
查看>>
ReferenceQueue的使用
查看>>
PHP FastCGI进程管理器PHP-FPM的架构
查看>>
referenceQueue用法
查看>>
Springboot处理跨域的方式(附Demo)
查看>>
php flush()刷新不能输出缓冲的原因分析
查看>>
Referenced classpath provider does not exist: org.maven.ide.eclipse.launchconfig
查看>>
Refactoring-Imporving the Design of Exsiting Code — 代码的坏味道
查看>>
PHP imap 远程命令执行漏洞复现(CVE-2018-19518)
查看>>
php include和require
查看>>
ref 和out 区别
查看>>