Home > Blockchain >  BASH How to get minimum value from each row
BASH How to get minimum value from each row

Time:12-03

I have csv file like this:

-0.106992, -0.106992, -0.059528, -0.059528, -0.028184, -0.028184, 0.017793, 0.017793, 0.0, 0.220367
-0.094557, -0.094557, -0.063707, -0.063707, -0.020796, -0.020796, 0.003707, 0.003707, 0.200767, 0.200767
-0.106038, -0.106038, -0.056540, -0.056540, -0.015119, -0.015119, 0.032954, 0.032954, 0.237774, 0.237774
-0.049499, -0.049499, -0.006934, -0.006934, 0.026562, 0.026562, 0.067442, 0.067442, 0.260149, 0.260149
-0.081001, -0.081001, -0.039581, -0.039581, -0.008817, -0.008817, 0.029912, 0.029912, 0.222084, 0.222084
-0.046782, -0.046782, -0.000180, -0.000180, 0.030788, 0.030788, 0.075928, 0.075928, 0.266452, 0.266452
-0.082107, -0.082107, -0.026791, -0.026791, 0.001874, 0.001874, 0.052341, 0.052341, 0.249779, 0.249779

enter image description here

I want to get the minimum value from each row.

Expected output must be:

-0.106992

-0.094557

-0.106038

-0.049499

-0.08100

-0.046782

-0.082107

I tried get it by awk but awk doesn't give minimum values:

awk command:

awk '{m=$1; for (i=2; i<=NF; i  ) if ($i < m) m = $i; print m}' file_name

output:

-0.028184,

-0.020796,

-0.015119,

-0.006934,

-0.008817,

-0.000180,

-0.026791,

CodePudding user response:

Perl makes short work of this:

perl -MList::Util=min -F', ' -E 'say min @F' file.csv
-0.106992
-0.094557
-0.106038
-0.049499
-0.081001
-0.046782
-0.082107

CodePudding user response:

Using any awk in any shell on every Unix box whether you have blanks after each comma or not:

$ awk -F', *' '{min=$1; for (i=2;i<=NF;i  ) if ($i<min) min=$i; print min}' file
-0.106992
-0.094557
-0.106038
-0.049499
-0.081001
-0.046782
-0.082107

CodePudding user response:

with ruby :-D

ruby -F', ' -ane 'puts $F.map(&:to_f).min' file.csv

CodePudding user response:

Your code is correct:

awk '{m=$1; for (i=2; i<=NF; i  ) if ($i < m) m = $i; print m}' file_name

Except that you must add a comma to the field separator:

awk -F '[[:blank:],]' '{m=$1; for (i=2; i<=NF; i  ) if ($i < m) m = $i; print m}' file_name

[[:blank:],] is spaces, tabs, and commas.

  • Related