简体   繁体   English

AWK - 比较后打印完整的输入字符串

[英]AWK - Print complete input string after comparison

I have a file a.text: 我有一个文件a.text:

hello world
my world
hello universe

I want to print the complete string if the second word is "world": 如果第二个单词是“world”,我想打印完整的字符串:

[root@sc-rdops-vm18-dhcp-57-128:/var/log] cat a | awk -F " " '{if($2=="world") print $1}'
hello
my

But the output which I want is: 但我想要的输出是:

[root@sc-rdops-vm18-dhcp-57-128:/var/log] cat a | awk -F " " '{if($2=="world") print <Something here>}'
hello world
my world

Any pointers on how I can do this? 有关如何做到这一点的任何指示?

Thanks in advance. 提前致谢。

awk '{if ($2=="world") {print}}' file

Output: 输出:

hello world
my world

First off, since you are writing a single if statement, you can use the awk 'filter{commands;}' pattern, like so 首先,由于您正在编写单个if语句,因此可以使用awk 'filter{commands;}'模式,就像这样

awk -F " " '$2=="world" { print <Something here> }'

To print the entire line you can use print $0 要打印整行,您可以使用print $0

awk -F " " '$2=="world"{print $0}' file

which can be written as 可以写成

awk -F " " '$2=="world"{print}' file

But {print} is the default action, so it can be omitted after the filter like this: {print}是默认操作,因此在过滤器之后可以省略它,如下所示:

awk -F " " '$2=="world"' file

Or even without the -F option, since the space is the default FS value 或者甚至没有-F选项,因为空间是默认的FS值

awk '$2=="world"' file

If you want / have to use awk to solve your problem: 如果你想/必须使用awk来解决你的问题:

 awk '$0~/world/' file.txt

If a line (ie, $0 ) matches the string "world" (ie, ~/world/ ) the entire line is printed 如果一行(即$0 )与字符串“world”匹配(即~/world/ ),则打印整行

If you only want to check the second column for world : 如果您只想检查world的第二列:

 awk '$2 == "world"' file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM