shell 根据关键字计算最大时间和内容的小例子

需要计算的文件如下:

cat total
Total elapsen time 29 seconds!
32346434423
234234234
234234
Total elapsen time 2 minutes 29 seconds!
121212312
123
2983123
68123
45123
23123
Total elapsen time 1 seconds!
97847
87563
936354
0846733
837636
Total elapsen time 99 seconds!

现在需要计算看这个文件中,浪费最多时间的文字内容。如上图:耗费时间最多的通过计算知道是Total elapsen time 2 minutes 29 seconds! ,那么文字就应该是她上面的三行,32346434423
234234234
234234
那么如何实现呢。可以通过以下几步

1、将文件中的分钟数去掉,计算出秒数;
2、得到最大的秒数,然后得到这个行数,
3、计算上面行数。
4、根据这2个行数,得到中间的内容,就是你的答案。

具体代码如下:

#!/bin/bash

#get the max number of delaytime
calcmaxnum_maxline()
{
        # get the line of times
        cat total | grep -n Total > time.log
        
	# get the useful word
        cat time.log | sed 's/Total elapsen time //' | sed 's/ minutes /*60+/' | sed 's/:/ /' | awk '{print $2}'> 1.log
        
	# line next line calc ,find the max number,then find the linecount of maxnumber
        max=`cat 1.log | head -n 1`
        cur=$max
        lines=`wc -l 1.log | awk '{print $1}'`
	for ((i=1;i<$lines;i++))
        do
                let ii=$i+1
                let cur=`cat 1.log | head -n $ii | tail -n 1`
                if [ $cur -gt $max ];then
                        max=$cur
                        let maxindex=$ii
                else
                        true
                fi
        done
}

# put maxindex in ,then calc to get the start line  and end line ,
# get text between start line to end line use head & tail ;
get_text()
{
	if [ $maxindex -le 1 ];then
		text=''
	fi
	#get the index of maxline number and (maxline-1) number ,so between is our text
	line=`cat time.log | head -n $maxindex |tail -n 1 | sed 's/:/ /' | awk '{print $1}'`
	let lineend=$line-1
	let linestart=$line-2
	text=`cat total | head -n $lineend | tail -n $linestart`
}

max=0
maxline=0
calcmaxnum_maxline
get_text 
echo -e "the bestet delay time is $max seconds \nand text is :\n$text "

rm -rf *.log

分享出来,做个例子,有不同方法的可以讨论共享。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

six2me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值