Search code examples
bashshellfileindexingminimum

Obtain index of the smallest number in a file


There is an input file 'data.txt' that contains the following numbers

11.0    22.0    33.0    -10.5    -2

How to find the value and index of the smallest number in the file. In that case the output will be

Value -10.5
Index 4

Solution

  • Break it to multiple lines using grep, attach line number (index) using cat -n and then sort on the value. For smallest number, choose the first record (head -1)

    # here is the file...
    $ cat data.txt
    11.0 22.0 33.0 0.5 44.0
    
    # here is the output you want
    $ grep -o '[^ ]\+' data.txt | cat -n | sort -g --key=2 | head -1
     4  0.5
    

    If you want the values in separate variables

    # store the value in a variable
    $ res=`grep -o '[^ ]\+' data.txt | cat -n | sort -g --key=2 | head -1 | xargs`
    
    # then cut out the data
    $ index=`echo $res | cut -f1 -d' '`
    $ value=`echo $res | cut -f2 -d' '`
    
    $ echo $index
     4
    $ echo $value
     0.5