如何使用 awk 打印字段与特定字符串匹配的行?
我有:
1 LINUX param1 value1
2 LINUXparam2 value2
3 SOLARIS param3 value3
4 SOLARIS param4 value4
我需要 awk 来打印 $2
为 LINUX
的所有行。
I have:
1 LINUX param1 value1
2 LINUXparam2 value2
3 SOLARIS param3 value3
4 SOLARIS param4 value4
I need awk to print all lines in which $2
is LINUX
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在
awk
中:请参阅
awk
示例< /a> 很好地介绍了awk
。在 sed 中:
请参阅
sed
通过示例 很好地介绍了sed
。In
awk
:See
awk
by Example for a good intro toawk
.In
sed
:See
sed
by Example for a good intro tosed
.在这种情况下,您可以使用漂亮的惯用
awk
:即:
awk
的默认操作是打印当前行。$2 == "LINUX"
就为 true,因此这将打印发生这种情况的那些行。如果您想打印所有与
LINUX
匹配的行,无论它是大写还是小写,请使用toupper()
将它们全部大写:或者使用以下语法之一的
IGNORECASE
:This is a case in which you can use the beautiful idiomatic
awk
:That is:
awk
when in a True condition is to print the current line.$2 == "LINUX"
is true whenever the 2nd field is LINUX, this will print those lines in which this happens.In case you want to print all those lines matching
LINUX
no matter if it is upper or lowercase, usetoupper()
to capitalize them all:Or
IGNORECASE
with either of these syntaxs:我的回答很晚了,但没有人提到:
My answer is very late, but no one has mentioned:
试试这些:
编辑:修改为不区分大小写
Try these out:
edit: modified for case insensitivity
我认为使用 awk 包含“精确”和“部分匹配”情况可能是个好主意))
因此,对于精确匹配:
对于部分匹配:
I think it might be a good idea to include "exact" and "partial matching" cases using
awk
))So, for exact matching:
And for partial matching:
在 GNU
sed
中,可以使用I
修饰符进行不区分大小写的匹配:将稳健地匹配“linux”、“Linux”、“LINUX”、“LiNuX”等第二个字段(在第一个字段之后,可能是任何非空白字符)并被任意数量(至少一个)的任何空白(主要是空格和制表符,尽管您可以使用
[:blank:]
将其严格限制为那些)。In GNU
sed
case-insensitive matches can be made using theI
modifier:Will robustly match "linux", "Linux", "LINUX", "LiNuX" and others as the second field (after the first field which may be any non-whitespace character) and surrounded by any amount (at least one) of any whitespace (primarily space and tab, although you can use
[:blank:]
to limit it to strictly those).