0
点赞
收藏
分享

微信扫一扫

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

萧萧雨潇潇 2022-01-20 阅读 43

需要计算的文件如下:

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

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

举报

相关推荐

0 条评论