Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AWK print specific column if chosen column is only numeric else print another column AIX

Is it possible to use an awk if condition to print a specific column if the chosen column is only values or characters?

below is an example:

echo "This is example test 1 for VAL1 value = int or VAL2 = string" | awk '{if ($5 == [0-9]) print $10 else print $14}'

OR:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

echo "This is example test one for VAL1 value = int or VAL2 = string" | awk '{if ($5 == [A-Z]) print $14; else print $10}'

The two examples above is determening from the awk if column 5 is all values or numbers and print a specific column based on column if whether it is only numbers or has string characters. In my example it can only be one or the either and not both mixed with numbers and characters.

How is it possible to do this using an awk?

>Solution :

Here is the problem:

$5 == [0-9]

In awk we use == operator for equality not for regex evaluation. We must use ~ for regex and also enclose a regex in /.../ notation.

So all of these awk solutions should work for you:

# check presence of a digit anywhere in the fifth field
awk '{print ($5 ~ /[0-9]/ ? $10 : $14)}'

# check if fifth field contains 1+ digits only
awk '{print ($5 ~ /^[0-9]+$/ ? $10 : $14)}'

# awk shorthand to check if $5 is numeric value
awk '{print ($5+0 == $5 ? $10 : $14)}'

Similarly to check an uppercase character use:

awk '{print ($5 ~ /[A-Z]/ ? $14 : $10)}'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading