RNB
RNB

Reputation: 99

Passing two values from awk to bash

I have a list of value in which I am looking for the highest and the lowest value using awk inside of bash. I am able to find these, but I'm unable to assign the values to some variable so I can use them in bash later on.

My input:

number  location  length  value

 1        2         40     0.96
---       5         45     0.97
 4        5         47     0.96
---       5         35     0.95
 2        5         60     0.95
---       3         55     0.96 

My awk command:

awk 'NR==1{max=$3; min=$3}{if ($3>max) max=$3; if ($3<min) min=$3;} END {print max,min}' List.txt

Output: 60 and 35.

I know it is possible to pass a value from bash to awk by declaring it in bash and again right at the beginning of my awk script with -v.

Variable1=string;
awk -v Variable1=$Variable '{}'

Is there a way to do the same thing, but from awk to bash so I can keep min and max?

Upvotes: 2

Views: 582

Answers (1)

anubhava
anubhava

Reputation: 785058

You can do:

read -r max min < <(awk 'NR==1{max=$3; min=$3}{if ($3>max) max=$3; if ($3<min) min=$3;} END {print max,min}' List.txt)

then:

echo $max
echo $min

OR:

arr=( $(awk 'NR==1{max=$3; min=$3}{if ($3>max) max=$3; if ($3<min) min=$3;} END {print max,min}' List.txt) )

then:

echo ${arr[0]} # max
echo ${arr[1]} # min

OR:

set -- $(awk 'NR==1{max=$3; min=$3}{if ($3>max) max=$3; if ($3<min) min=$3;} END {print max,min}' List.txt)

then:

max=$1
min=$2

Upvotes: 8

Related Questions