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

你可能感兴趣的文章
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
查看>>
org.springframework.beans.factory.BeanDefinitionStoreException
查看>>
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>