获取文件中最小数字的索引

Obtain index of the smallest number in a file

有一个输入文件 'data.txt' 包含以下数字

11.0    22.0    33.0    -10.5    -2

如何找到文件中最小数字的值和索引。在这种情况下,输出将是

Value -10.5
Index 4

使用 grep 将其分成多行,使用 cat -n 附加行号(索引),然后在值上添加 sort。对于最小的数字,选择第一条记录 (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

如果您想要单独变量中的值

# 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

使用 Perl 一行代码

> cat data.txt
11.0    22.0    33.0    0.5    44.0
> perl -lane ' {@arr=sort @F;foreach(@F) { $x++;  print "$x $_" if $arr[0]==$_ } }' data.txt
4 0.5
>