TransWikia.com

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

Unix & Linux Asked by ssiresha garimella on August 10, 2020

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.

3 Answers

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

Correct answer by rkhff on August 10, 2020

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

Answered by Rakesh Sharma on August 10, 2020

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: %dn", max, min); }

Usage:

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

Answered by Ainar-G on August 10, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP