我正在尝试跳过对End_time值为"Failed"的列和行的操作。
这是我的实际档案。
check_time.log
Done City Start_time End_time
Yes Chicago 18 10
Yes Atlanta 208 11
No Minnetonka 57 Failed
Yes Hopkins 112 80
No Marietta 2018 Failed
这是我迄今为止所拥有的。
awk 'BEGIN { OFS = "t" } NR == 1 { $5 = "Time_diff" } NR >= 2 { $5 = $3 - $4 } 1' < files |column -t
输出:
Done City Start_time End_time Time_diff
Yes Chicago 18 10 8
Yes Atlanta 208 11 197
No Minnetonka 57 Failed 57
Yes Hopkins 112 80 32
No Marietta 2018 Failed 2018
所需输出应如下所示:
Done City Start_time End_time Time_diff
Yes Chicago 18 10 8
Yes Atlanta 208 11 197
No Minnetonka 57 Failed
Yes Hopkins 112 80 32
No Marietta 2018 Failed
那我该怎么跳过呢?
您应该能够更改:
$5 = $4 - $5
进入:
if ($4 != "Failed") { $5 = $3 - $4 }
这将:
- 拒绝将
$5
从空更改为结束时间为Failed
的行中的计算值;以及 - 正确计算所有其他行
我说是正确的,因为在这些情况下,你似乎想要开始时间减去结束时间,尽管事实上持续时间往往是结束时间减去开始时间。我已经更改了它以匹配您想要的输出,而不是"理智"的期望。
下面是一份成绩单,你可以看到它的作用:
pax$ awk 'BEGIN{OFS="t"}NR==1{$5="Time_diff"}NR>=2{if($4!="Failed"){$5=$3-$4}}1' <inputFile.txt |column -t
Done City Start_time End_time Time_diff
Yes Chicago 18 10 8
Yes Atlanta 208 11 197
No Minnetonka 57 Failed
Yes Hopkins 112 80 32
No Marietta 2018 Failed
顺便说一句,当您开始从New York
、San Antonio
、Salt Lake City
或更糟的Maccagno con Pino e Veddasca
:-(获取信息时,您可能想考虑会发生什么
请您尝试以下操作。(考虑到Input_file的最后一个字段将仅按此顺序排列,不会有任何其他附加字段,如果有,则您可能需要调整字段号,因为如果您所在城市的值中有空格,则从开始的字段号将在简单地区分所有行的值时产生问题,因为字段值会因行而异(
awk '
FNR==1{
print $0,"Time_Diff"
next
}
$NF!="Failed"{
$(NF+1)=$(NF-1)-$NF
}
1
' Input_file | column -t
输出如下。
Done City Start_time End_time Time_Diff
Yes Chicago 18 10 8
Yes Atlanta 208 11 197
No Minnetonka 57 Failed
Yes Hopkins 112 80 32
No Marietta 2018 Failed
解释:现在添加以上代码的完整解释。
awk ' ##Starting awk program from here.
FNR==1{ ##Checking conditoin if line is very first line then do following.
print $0,"Time_Diff" ##Printing current line with string Time_Diff here on very first line to print headings.
next ##next is awk keyword which will skip all further statements from here.
}
$NF!="Failed"{ ##Checking if last field $NF where NF is number of fields and $ means in awk field value is NOT failed then do following.
$(NF+1)=$(NF-1)-$NF ##Add a new column by doing $(NF+1) whose value will be difference of 2nd last column and last column as per samples.
} ##Closing this condition block here.
1 ##Mentioning 1 will print edited/non-edited line for Input_file.
' Input_file | ##Mentioning Input_file name and passing awk program output to next command by using pipe(|).
column -t ##Using column -t will print the output in TAB separated format.
如果您正在考虑Perl,
> cat kwa.in
Done City Start_time End_time
Yes Chicago 18 10
Yes Atlanta 208 11
No Minnetonka 57 Failed
Yes Hopkins 112 80
No Marietta 2018 Failed
> perl -lane ' print join(" ",@F,"Time_Diff") if $.==1; if($.>1 ) { $F[4]=$F[2]-$F[3] if not $F[3]=~/Failed/; print join(" ",@F) } ' kwa.in | column -t
Done City Start_time End_time Time_Diff
Yes Chicago 18 10 8
Yes Atlanta 208 11 197
No Minnetonka 57 Failed
Yes Hopkins 112 80 32
No Marietta 2018 Failed
>