Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison in awk

Tags:

syntax

string

awk

I need to compare two strings in alphabetic order, not only equality test. I want to know is there way to do string comparison in awk?

like image 731
Dagang Avatar asked May 26 '11 13:05

Dagang


People also ask

What is == in awk?

<= – less than or equal to. == – equal to. !=

How do you compare values in awk?

In awk, any nonzero numeric value or any nonempty string value is true. Any other value (zero or the null string, "") is false. In other words, if the field is not "0" or "", it is true. So if you are looking for (expecting) a 0, you are expecting the comparison to be false.


2 Answers

Sure it can:

pax$ echo 'hello goodbye' | gawk '{if ($0 == "hello") {print "HELLO"}}' HELLO 

You can also do inequality (ordered) testing as well:

pax> printf 'aaa\naab\naac\naad\n' | gawk '{if ($1 < "aac"){print}}' aaa aab 
like image 100
paxdiablo Avatar answered Sep 19 '22 14:09

paxdiablo


You can do string comparison in awk using standard boolean operators, unlike in C where you would have to use strcmp().

echo "xxx yyy" > test.txt

cat test.txt | awk '$1!=$2 { print($1 $2); }'

like image 43
Ilya Matveychikov Avatar answered Sep 19 '22 14:09

Ilya Matveychikov