如何使用 awk 提取具有精确匹配的行 [英] How to use awk to extract a line with exact match

查看:83
本文介绍了如何使用 awk 提取具有精确匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 awk 在文件中搜索精确匹配项?

How do I use awk to search for an exact match in a file?

test.txt
hello10
hello100
hello1000

我尝试了以下操作,它返回所有 3 行

I have tried the following and it returns all 3 lines

awk '$0 ~ /^hello10/{print;}' test.txt

grep -w hello10 可以解决问题,但在这个盒子上,grep 版本非常有限,而且只有几个开关可用

grep -w hello10 does the trick but on this box grep version is very limited and only few switches available

推荐答案

要进行整行正则表达式匹配,您需要使用 ^ 和 <代码>$:

To do a full line regular expression match you need to anchor at the beginning and the end of the line by using ^ and $:

$ awk '/^hello10$/' test.txt
hello10

但是除了我们刚刚添加的锚定之外,您实际上并没有使用任何正则表达式功能,这意味着您实际上想要简单的旧字符串比较:

But you're not actually using any regular expression features beside the anchoring we just added which means you actually want plain old string comparison:

$ awk '$0=="hello10"' test.txt
hello10

这篇关于如何使用 awk 提取具有精确匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆