Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK - Print complete input string after comparison

Tags:

bash

awk

I have a file a.text:

hello world
my world
hello universe

I want to print the complete string if the second word is "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.

like image 704
Aditya Kotwal Avatar asked Nov 23 '25 07:11

Aditya Kotwal


2 Answers

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

Output:

hello world
my world
like image 73
Cyrus Avatar answered Nov 24 '25 22:11

Cyrus


First off, since you are writing a single if statement, you can use the awk 'filter{commands;}' pattern, like so

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

To print the entire line you can use 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:

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

Or even without the -F option, since the space is the default FS value

awk '$2=="world"' file
like image 30
user000001 Avatar answered Nov 24 '25 22:11

user000001



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!