从文件中提取模式并减去接收的值

时间:2018-04-11 05:54:35

标签: linux shell awk grep

这是我到目前为止的代码

grep -i "start" logs.txt | awk '{print $3}'
grep -i "end" logs.txt | awk '{print $3}'

因此,如果start的值为10且end为30.我如何减去此值并得到20作为输出。

示例文件:logs.txt

start_value : 10
end_value : 30
start_value : 20
end_value : 50

期望的输出:

differance1 : 20
differance2 : 30

3 个答案:

答案 0 :(得分:1)

尝试:

$ awk '/start/ {a=$3} /end/{n++; printf "differance%s : %s\n",n,$3-a}' logs.txt
differance1 : 20
differance2 : 30

工作原理:

  • /start/ {a=$3}

    每当我们到达start行时,我们会将变量a中的起始值保存。

  • /end/{n++; printf "differance%s : %s\n",n,$3-a

    每当我们到达end行时,我们就会打印出结果。

答案 1 :(得分:1)

关注awk可能对您有帮助。

awk '/start_value/{start=$NF} /end_value/{print "difference"++i" : " $NF-start;start=""}' Input_file

上述代码说明:

awk '
/start_value/{  start=$NF                            } ##Searching for a string start_value in current line if found creating variable named start with value $NF.
/end_value/  {  print "difference"++i" : " $NF-start;  ##Searching for a string end_value and then printing string difference with variable i increasing value and printing the different of $NF and start variable here.
                start=""                             } ##Nullifying the variable start here so that in case any line is empty it should not take previous value of it.
' Input_file                                           ##Mentioning Input_file name here.

答案 2 :(得分:0)

#!/bin/bash

awk '
    function calcul(){
        split(start, st, ":")   # st[1]=hour, st[2]=minutes, st[3]=seconds
        split(end, en, ":")     # en[1]=hour, en[2]=minutes, en[3]=seconds
        start = st[1] * 3600 + st[2] * 60 + st[3]   # seconds
        end = en[1] * 3600 + en[2] * 60 + en[3]     # seconds   # print en[3] en[2] en[1]
        diff_sec = end - start                      # seconds
        diff=sprintf( "%d:%s", diff_sec/60, diff_sec % 60 ) # format M:S
        start = end = ""
    }
    /^start/ { start = $3 }
    /^end/   { end   = $3; calcul(); print diff_sec, "s  ", diff }
' logs.txt

测试文件

cat << end > logs.txt
start_time : 10:30:00
end_time : 10:45:00
start_time : 04:20:00
end_time : 05:20:30
end

输出

900 s   15:0
3630 s   60:30