if条件在while迭代循环bash中 [英] if condition on while iteration loop bash

查看:70
本文介绍了if条件在while迭代循环bash中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其内容如下:

I have a file with contents like below;

864440 17:59:48.143
864440 17:59:48.221
864441 17:59:48.159
864441 17:59:48.221
864442 17:59:48.159
864442 17:59:48.237
864443 17:59:48.174
864444 17:59:48.190
864444 17:59:48.253
864445 17:59:48.206
864445 17:59:48.268
864446 17:59:48.221
864446 17:59:48.284

我正在执行while循环以读取第一个和第二个值,并将其放在如下所示的变量中;

I am doing a while loop to read the 1st and 2nd value and put it on a variable like below;

while read list; do
     jbnum=`echo $list|awk '{print $1}'`
     time=`echo $list|awk '{print $2}'`
done < jobstmp.txt

我想添加一个if条件,如果jbnum等于下一个迭代,它将获得相同作业编号的时差,否则将不执行任何操作并进入下一个迭代

I would like to add an if condition that if the jbnum is equal to the next iteration it would get the time difference of the same job number if not then do nothing and go to next iteration

感谢所有根据Chris Maes提供的代码回答了以下解决方案的人

Thanks for all those who answered the solution below based on the code provided by Chris Maes

while read jobnum time
do
    if [[ "$prevjobnum" == "$jobnum" ]]
    then
        ENDTIME=`date +%s.%N -d "$time"`
        STARTTIME=`date +%s.%N -d "$prevtime"`
        DIFF=$(echo $ENDTIME - $STARTTIME | bc | sed 's/0\{1,\}$//')

        echo "$prevjobnum time is $DIFF seconds"
    fi
    # keep variables for next iteration
    prevjobnum=$jobnum
    prevtime=$time
done < jobstmp.txt

推荐答案

您无法提前阅读.您将不得不使用一些中间变量.类似于(请注意,您可以立即读取多个变量):

you cannot watch ahead with read. You'll have to use some intermediate variables; something like (note that you can immediately read multiple variables):

while read jobnum time
do
    if [[ "$prevjobnum" == "$jobnum" ]]
    then
        #do your stuff with the variables $prevjobnum and $prevtime. for example:
        echo "prevjobnum=$prevjobnum , prevtime=$prevtime"
    fi
    # keep variables for next iteration
    prevjobnum=$jobnum
    prevtime=$time
done < jobstmp.txt

这给出了:

prevjobnum=864440 , prevtime=17:59:48.143
prevjobnum=864441 , prevtime=17:59:48.159
prevjobnum=864442 , prevtime=17:59:48.159
prevjobnum=864444 , prevtime=17:59:48.190
prevjobnum=864445 , prevtime=17:59:48.206
prevjobnum=864446 , prevtime=17:59:48.221

这篇关于if条件在while迭代循环bash中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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