Tree55Topz
Tree55Topz

Reputation: 1142

Bash - finding minimum number per line

I am trying to get more familiar with awk statements, especially ones that can be done with just one line. I have a file that looks like this

9 5 0 2
8 7 4 3
4 8 2 1

I want the output to look like

0
3
1

Is there a way I can do this with just a one liner using awk? Thank you.

Upvotes: 1

Views: 153

Answers (3)

Mark Plotnick
Mark Plotnick

Reputation: 10271

GNU awk, which you'll find in most Linux distributions, has a built-in sort function, asort.

echo -e "9 5 0 2\n8 7 4 3\n4 8 2 1" | 
    awk '{ split($0,a); asort(a); print a[1]; }'
0
3
1

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247022

The are languages with built-in "min" functions:

ruby -ane 'puts $F.min' file

Or available libraries

perl -MList::Util=min -lane 'print min @F' file

Limiting to shell:

min() { printf "%s\n" "$@" | sort -n | head -1; }
while read -a nums; do
    echo $(min "${nums[@]}")
done < file

Upvotes: 3

anubhava
anubhava

Reputation: 785551

Using awk:

awk '{min=$1; for (i=2; i<=NF; i++) if ($i < min) min=$i; print min}' file
0
3
1

Upvotes: 3

Related Questions