首页 > 解决方案 > 在 shell 脚本的间隔中查找数据集之间的持续时间及其最大值

问题描述

这与我的旧问题有关Find the durations and their maximum between the dataset in shell script

我有一个数据集:

ifile.txt
2
3
2
3
2
20
2
0
2
0
0
2
1
2
5
6
7
0
3
0
3
4
5

我想找出 6 个值区间中 0 个值之间的不同持续时间及其最大值。

我的愿望输出是:

ofile.txt
6 20
1 2
1 2
1 2
5 7
1 3
3 5

在哪里

6 is the number of counts until next 0 within 6 values (i.e. 2,3,2,3,2,20) and 20 is the maximum value among them;
1 is the number of counts until next 0 within next 6 values (i.e. 2,0,2,0,0,2) and 2 is the maxmimum;
Next 1 and 2 are withing same 6 values;
5 is the number of counts until next 0 within next 6 values (i.e. 1,2,5,6,7,0) and 7 is the maximum among them;
And so on

根据我上一个问题的答案,我正在尝试这个:

awk '(NR%6)==0
$0!=0{
  count++
  max=max>$0?max:$0
}
$0==0{
  if(count){
      print count,max
  }
  count=max=""
}
END{
  if(count){
      print count,max
  }
}
'  ifile.txt

标签: shellawk

解决方案


添加到RavinderSingh13 给出的EDIT2解决方案的格式命令将打印确切的期望输出:

awk '
$0!=0{
  count++
  max=max>$0?max:$0
  found=""
}
$0==0{
  print count,max
  count=max=0
  next
}
FNR%6==0{
  print count,max
  count=max=0
  found=1
}
END{
  if(!found){
      print count,max
  }
}
'  Input_file | awk '!/^ /' | awk '$1 != 0'

输出如下。

6 20
1 2
1 2
1 2
5 7
1 3
3 5


EDIT2:添加另一个解决方案,它将打印每 6 个元素中的值以及介于两者之间的零。

awk '
$0!=0{
  count++
  max=max>$0?max:$0
  found=""
}
$0==0{
  print count,max
  count=max=0
  next
}
FNR%6==0{
  print count,max
  count=max=0
  found=1
}
END{
  if(!found){
      print count,max
  }
}
'  Input_file

输出如下。

6 20
1 2
1 2
0 0
1 2
5 7
1 3
3 5


编辑:根据 OP 的评论,当在这种情况下出现零值时,OP 不想重置非零的计数,请尝试以下操作。

awk '
$0!=0{
  count++
  max=max>$0?max:$0
  found=""
}
FNR%6==0{
  print count,max
  count=max=0
  found=1
}
END{
  if(!found){
      print count,max
  }
}
'  Input_file

输出如下。

6 20
3 2
5 7
.......


您能否尝试以下操作(仅使用已发布的示例进行编写和测试)。

awk '
$0!=0{
  count++
  max=max>$0?max:$0
  found=""
}
$0==0{
  count=FNR%6==0?count:0
  found=""
}
FNR%6==0{
  print count,max
  count=max=0
  found=1
}
END{
  if(!found){
      print count,max
  }
}
'  Input_file

推荐阅读