简体   繁体   中英

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.

Using awk:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM