Home > Software engineering >  awk condiontals for grep like things and sum of the two
awk condiontals for grep like things and sum of the two

Time:08-25

I have a Data in a file where I have some numbers with denomination like GB & TB and i have to sum them together .

Below is file data:

$ cat data_in_transit| awk '/TB/{print $6}'
1.26TB
1.24TB
2.85TB
1.03TB
1.07TB
1.01TB

$ cat data_in_transit| awk '/GB/{print $6}'
962.2GB
1005GB
892.5GB
910.0GB
823.4GB
1008GB
426.4GB
168.6GB
208.1GB
511.3GB
787.5GB
448.0GB
509.6GB
496.1GB
550.7GB

I can calculate them individually, however i want below two to be summ'ed into one query.

Anything starting with GB ..

$ awk '/GB/{sumGB =$6}END{printf ("%.2f\n", sumGB / 1024)}' seoul_data_in_transit
9.48

Anything starting with TB ..

$ awk '/TB/{sumTB =$6}END{printf ("%.2f\n", sumTB)}' seoul_data_in_transit
8.46

please suggest .

CodePudding user response:

awk '$6~/GB/{s =$6}$6~/TB/{s =$6 * 1024}END{print s/1024,"TB"}' file

CodePudding user response:

Assuming the current summation code generates the correct results:

awk '
/GB/ { sumGB =$6 }
/TB/ { sumTB =$6 }
END  { printf ("%.2f GB\n", sumGB / 1024)
       printf ("%.2f TB\n", sumTB)
     }
' seoul_data_in_transit

Which should generate:

9.48 GB
8.46 TB
  • Related