Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using awk with column value conditions

Tags:

linux

shell

awk

People also ask

How do you use awk with conditions?

The conditional statement executes based on the value true or false when if-else and if-elseif statements are used to write the conditional statement in the programming. Awk supports all types of conditional statements like other programming languages.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What does $1 $2 indicate in awk file?

Awk works by scanning through each line of text (or record) in the file and carrying out any instructions you tell it on that line. In awk we access fields using syntax like: $1 or $2. $1 indicates that you are referring to the first field or first column.

How do you use the field separator in awk?

Any special characters in the field separator must be escaped appropriately. For example, to use a ' \ ' as the field separator on the command line, you would have to type: # same as FS = "\\" awk -F\\\\ '…' files … Because ' \ ' is used for quoting in the shell, awk sees ' -F\\ '.


If you're looking for a particular string, put quotes around it:

awk '$1 == "findtext" {print $3}'

Otherwise, awk will assume it's a variable name.


This method uses regexp, it should work:

awk '$2 ~ /findtext/ {print $3}' <infile>

Depending on the AWK implementation are you using == is ok or not.

Have you tried ~?. For example, if you want $1 to be "hello":

awk '$1 ~ /^hello$/{ print $3; }' <infile>

^ means $1 start, and $ is $1 end.


This is more readable for me

awk '{if ($2 ~ /findtext/) print $3}' <infile>