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 else statement not working converting bytes in column to mb and gb and tb

Trying to reformat bytes in column to mb and gb based on if else.

awk -F ',' '{if ($NF >= "1073741824") {$NF=$NF/1024/1024/1024; gsub(/.*/, "&GB", $NF)} else { $NF=$NF/1024/1024; gsub(/.*/, "&MB", $NF)}}1'

But else statement is not working. If bytes are greater than or equal to 1gb convert it to gb else to mb.

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

>Solution :

One general issue is with the conditional; the current code is performing a string comparison when it should be performing a numeric comparison.

Consider:

# string comparison ($1 >= "300")

$ echo 100000 | awk '{if ($1 >= "300") print "greater than 300"}'
    - returns nothing

# numeric comparison ($1 >= 300)

$ echo 100000 | awk '{if ($1 >= 300) print "greater than 300"}'
greater than 300

Rolling this into OP’s code (remove double quotes from around the 1073741824:

# old:
awk -F ',' '{if ($NF >= "1073741824") {$NF=$NF/1024/1024/1024; gsub(/.*/, "&GB", $NF)} else { $NF=$NF/1024/1024; gsub(/.*/, "&MB", $NF)}}1'
                        ^^^^^^^^^^^^

# new:
awk -F ',' '{if ($NF >=  1073741824 ) {$NF=$NF/1024/1024/1024; gsub(/.*/, "&GB", $NF)} else { $NF=$NF/1024/1024; gsub(/.*/, "&MB", $NF)}}1'
                         ^^^^^^^^^^

If this edit of the current code does not address the issue then please update the question with the updated code, sample input, (wrong) output generated by the code and the (correct) expected output.

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