1

How to print max and min value of a column in txt file into variable?

abc.txt:

col1 col2
1    35
1    20
1    40
1    50

I have written code to identify max and min value

cut -f2 -d "" abc.txt|head -1
cut -f2 -d "" abc.txt|tail -1
v1 = 'echo <??>|cut -f2 -d "" abc.txt|head -1'
v2 = 'echo <??>|cut -f2 -d "" abc.txt|tail -1'

But I am unable to put it into variable, I need to use it in a loop. I will not be writing a while read line, because it prints everyline.

1

There are so many ways to do this. Like Ainar-G I'd use Awk:

$ cat abc.txt 
col1  col2
1 35
1 20
1 40
1 50

The below ignores lines containing the pattern 'col'; grabs the second column in the file; and then sorts the numbers:

$ min=$(awk '!/col/ {print $2}' abc.txt | sort -nr | tail -1)
$ max=$(awk '!/col/ {print $2}' abc.txt | sort -nr | head -1)

$ echo "$min"
20

$ echo "$max"
50
0

Awk program:

FNR == 1 { next; }

FNR == 2 { max = min = $2; next }

{
    if ($2 > max) {
        max = $2; 
    } else if ($2 < min) {
        min = $2;
    }
}

END { printf("max: %d, min: %d\n", max, min); }

Usage:

$ awk -f ./tmp.awk ./tmp.txt
max: 50, min: 20
0

Math operations can also be done using the desk calculator dc utility in Linux. It operates on data present on its stack. And when we read a line using the ? command, it places operands (space separated) on the stack. It involves recursively calling commands stored in registers. You can read more in gnu dc manual.

$ if="abc.txt"
$ declare -a a=($(< "$if" tr x- x_ | sed 1d | dc -e "
[q]sq [sMd]sa [sNd]sb
[?z0=qddlM<adlN>bcz0=?]s?
?c ?dsMsN cl?x lMlNf"))
$ min=${a[0]} max=${a[1]}
$ echo "min:$min nax:$max"

min:20 max:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.