查找最大值和最小值并从文件中打印行 [英] Finding the max and min values and printing the line from a file

查看:128
本文介绍了查找最大值和最小值并从文件中打印行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,在第一列中有数字.

I have a file which has numbers at the first column.

100,red
101,blue
102,black

我应该编写一个shell脚本,它将打印带有最大和最小数字的行.

I should write a shell script that it will print the line with the max and min numbers.

max=0
cat file.txt|while read LINE
do
    fir=`echo $LINE|awk '{print $2}'`
    sec=`echo $LINE|awk '{print $3}'`
    if [ $fir -gt $max ]; then
       max=$fir
    fi
    if [ $sec -gt $max ];then
        max=$sec
    fi
done

grep $max file.txt

这是我到目前为止为找到最大值而尝试的方法.

This is what i tried so far for finding the max.

推荐答案

最小值:

[bash]$ cut -f1 -d"," file_name | sort -n | head -1

对于最大值:

[bash]$ cut -f1 -d"," file_name | sort -n | tail -1

这篇关于查找最大值和最小值并从文件中打印行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆