我有包含 8 个字段的输入行。这样:
Field1 Field2 Field3 Field4 Field5 Field6 Field7 Field8
name ID number stuff Jan15 ? 00:00:00 some command
其中一个字段 Field7 是一个时间戳,如下所示00:00:00
我想"扫描"第 7 个字段,看看时间是否大于一分钟,即第 7 个字段是否大于 00:01:00。
如果第 7 个字段更大,我想将字段 2 7 和 8 的值打印到一个文件中。我对awk的经验很少,但据我所知,这就是我想使用的工具。
EDIT1:
要使用ps
命令运行它,请使用如下方式:
ps -ef | awk '
{
split($7,array,":")
tot_time=array[2]*60+array[3]
if(tot_time>60){
print $2,$7,$8
}
tot_time=""
delete array
}
'
还要覆盖进程运行正好 1 小时且不到 1 分钟的 1 种边缘情况:)尝试以下。
ps -ef | awk '
{
split($7,array,":")
tot_time=array[1]*3600+array[2]*60+array[3]
if(tot_time>60){
print $2,$7,$8
}
tot_time=""
delete array
}
'
您能否尝试以下操作。将第 7 列分成 3 个不同的部分(小时、分钟和秒(,将分隔符作为:
,然后从中计算分钟以检查其值是否超过 60。
awk '
{
split($7,array,":")
tot_time=array[2]*60+array[3]
if(tot_time>60){
print $2,$7,$8
}
tot_time=""
delete array
}
' Input_file
用样品测试:
cat Input_file
Field1 Field2 Field3 Field4 Field5 Field6 Field7 Field8
xxx xxx xxx xxx xxx xxx 00:01:01 xxx
xxx xxx xxx xxx xxx xxx 00:00:48 xxx
运行代码后,输出如下。
awk '
{
split($7,array,":")
tot_time=array[2]*60+array[3]
if(tot_time>60){
print $2,$7,$8
}
tot_time=""
delete array
}
' Input_file
xxx 00:01:01 xxx
假设字段由空格或制表符分隔,怎么样:
awk '$7 > "00:01:00" {print $2, $7, $8}' file
输入:
name1 ID1 number1 stuff Jan15 ? 00:00:59 somecommand1
name2 ID2 number2 stuff Jan15 ? 00:01:00 somecommand2
name3 ID3 number3 stuff Jan15 ? 00:01:01 somecommand3
name4 ID4 number3 stuff Jan15 ? 00:02:00 somecommand4
输出:
ID3 00:01:01 somecommand3
ID4 00:02:00 somecommand4
Awk 主要将两个字符串比较为strings
,除非两者都是数字 值或一个是数字,另一个是数字字符串。
在这种情况下,string comparison
执行,然后您可以直接 比较 HH:MM:SS 表示中的时间字符串。
假设您的文件是空格/制表符分隔的,这应该可以解决问题:
awk '$7!~/^(00:01:00|00:00)/{print $2,$7,$8}' file > out_file
如果您有以下输入文件:
Field1 Field2 Field3 Field4 Field5 Field6 Field7 Field8
name ID number stuff Jan15 ? 00:00:14 somecommand
name2 ID2 number2 stuff Jan15 ? 00:00:30 somecommand2
name3 ID3 number3 stuff Jan15 ? 00:01:30 somecommand3
name4 ID4 number4 stuff Jan15 ? 01:01:30 somecommand4
name5 ID5 number5 stuff Jan15 ? 01:00:00 somecommand5
name6 ID6 number6 stuff Jan15 ? 00:01:00 somecommand5
您可以使用以下awk
命令
awk '$7 !~ /(^00:00|00:01:00)/ || NR==1 {print $2,$7,$8}' f.in | column -t
它将给出输出:
Field2 Field7 Field8
ID3 00:01:30 somecommand3
ID4 01:01:30 somecommand4
ID5 01:00:00 somecommand5
解释:
- 基于正则表达式的方法
NR==1
打印第一行(如果不需要,可以删除此部分(- 该模式不以
00:00
开头或不等于00:01:00
,如果您将约束更改为大于或等于 1 分钟,则可以将其删除 - 打印必填字段
column -t
用于漂亮的输出,可以删除。