[英]How to calculate time difference of args in awk
I have input in below format 我以以下格式输入
0001580-160219044548744-oozie-oozi-W@:start: - - - - OK :start: 0 - :START: 2016-02-24 13:34:46 GMT OK 2016-02-24 13:34:46 GMT
0001580-160219044548744-oozie-oozi-W@PrepareHDFS - - - - OK PrepareHDFS 0 - fs 2016-02-24 13:34:46 GMT OK 2016-02-24 13:34:47 GMT
Using awk I am trying to print the required columns positioned in 7,12,16 Columns as below using the below command 使用awk,我正在尝试使用以下命令打印位于7、12、16列中的所需列,如下所示
cat input | awk '/^000/ {printf "%-40s %-10s %-10s",$7,$12,$16}'
and the output is 输出是
:start: 05:35:56 05:35:56
PrepareHDFS 05:35:56 05:35:57
My requirement is along with the above output I need time difference also. 我的要求是与上面的输出一起我也需要时差。 I tried below one inside a script
我在脚本里面尝试了一个
cat intput | awk '/^000/ {printf "%-40s %-10s %-10s",$7,$12,$16;
T1=`date +%s -d $12`;T2=`date +%s -d $16`;
DIFF=`expr ${SEC2} - ${SEC1}`; print `date +%H:%M:%S -ud ${DIFF}` }'
But I am getting errors as invalid syntax. 但是我收到错误作为无效的语法。 How can I achieve the time difference so that output should be
我如何获得时差,以便输出
PrepareHDFS 05:35:56 05:35:57 00:00:01
ScheduleStart 05:35:57 05:36:11 00:00:14
EDIT: 编辑:
For time difference, I have below script 对于时差,我有以下脚本
TIME1=05:36:27
TIME2=05:36:51
SEC1=`date +%s -d ${TIME1}`
SEC2=`date +%s -d ${TIME2}`
DIFFSEC=`expr ${SEC2} - ${SEC1}`
echo `date +%H:%M:%S -ud @${DIFFSEC}`
00:00:24
Can I use this set of lines inside a function, and call that function from awk? 我可以在函数内使用这组线,并从awk调用该函数吗?
You can do it using awk
, it's just a bit … unweildy: 您可以使用
awk
来做到这一点,这只是一点点……不妙:
awk -v cmd='date +%s -d ' -v cmd2='date +%H:%M:%S -d ' '/^000/ {
cmd $12 | getline T1; close(cmd $12);
cmd $16 | getline T2; close(cmd $16);
cmd2 (T2 - T1) | getline T1; close(cmd2 (T2 - T1));
printf "%-40s %-10s %-10s%-10s\n", $7, $12, $16, T1
}'
You can't use the shell's backtick process substitution in awk
. 您不能在
awk
使用shell的反引号过程替换。 awk
has its own way of getting the output of a command - via getline
and coprocesses . awk
通过getline
和coprocesses有其自己的获取命令输出的方式。 The syntax is roughly: 语法大致为:
command | getline var-name
close(command)
Where command
is a variable or string containing the command. 其中
command
是包含命令的变量或字符串。 cmd $12
is just the concatenation of cmd
and $12
, so the command would become date +%s -d 13:34:46
, for example. cmd $12
只是cmd
和$12
的串联,因此该命令将成为date +%s -d 13:34:46
。
date
interpretation of pure numbers as input is complex. 纯数字作为输入的
date
解释很复杂。 It would be best to force it see the input number as a Unix timestamp, by using a leading @
: 最好通过使用前导
@
来强制将输入数字视为Unix时间戳。
awk -v cmd='date +%s -d ' -v cmd2='date +%H:%M:%S -d @' '/^000/ {
cmd $12 | getline T1; close(cmd $12);
cmd $16 | getline T2; close(cmd $16);
cmd2 (T2 - T1) | getline T3; close(cmd2 (T2 - T1));
printf "%-40s %-10s %-10s%-10s\n", $7, $12, $16, T3
}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.