String Comparison in 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?

2

3 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
5

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); }'

3

You can check the answer in the nawk manual

echo aaa bbb | awk '{ print ($1 >= $2) ? "true" : "false" }'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest