The Linux shell implementation asks for the maximum and minimum value of a multidimensional array _linux shell

Source: Internet
Author: User

My colleague sent a shell question to find the maximum and minimum values in a multidimensional array.
such as file 99file:

33 55 23 56 99
234 234 545 6546 34
11 43 534 33 75
43 34 76 756 33
343 890 77 667 55

One of my implementations:

#! /bin/bash
echo "The file is:"
cat 99shu
max=0
min=999999
line=1
dnum=$ (cat 99shu| WC-L) while
(($line <= $dnum)) does for
I in
$ (cat 99shu|head-"$line")
    do
  ((max< $i)) & &max= $i
    ((min> $i)) &&min= $i done by let
++line do
 
echo "The max number is: $ Max "
echo" the min number is: $min

Results:

The max number is:6546
The min number is:11

Implementation of the second:

#! /bin/bash
# echo the MAX and the MIN

echo "The numbers is:"
cat 99shu
mnum=0
min=99999
While the read line does
declare-a arr= ($line)
lnum=$ (echo $line | wc-w)
i=0 while
($i <$ Lnum))
do
(($mnum <${arr[i]})) && Mnum=${arr[i]}
(($min >${arr[i)})) && min=${ Arr[i]} Let
++i
do
< 99shu
echo "The max number is $mnum"
echo "the min number is $min"

Achieve 3, powerful awk

#! /bin/bash
echo "The MAX number is: $ (cat 99shu | awk ' {for (i=1;i<=nf;i++) if (max< $i) max= $i;p rint max} ' |tail-1 ' "
echo" eht MIN number is: $ (cat 99shu | awk ' {min=999999;for (i=1;i<=nf;i++) if (min> $i) min= $i;p rint min} ' |sort|head-1 '

Implementation 4:

#!/bin/bash
min=$ (cat  99shu | tr "T" "\ n" |tr "" \ n "|sort-n|uniq|grep-v" ^$ "|head-1)
max=$ (cat  99shu |  TR "\ \ n" \ |tr "" "\ n" |sort-n|uniq|grep-v "^$" |tail-1)
echo "The MAX number is $max"
echo "the MIN number is $min "

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.