shell - 在 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
解决方案
添加到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
推荐阅读
- html - 将容器居中到页面中间
- csv - AWS 胶水:当 CSV 包含字符串和时间戳/日期值时,爬虫无法识别元数据
- wordpress - 如何使用 wp-cron 一次性创建执行功能
- python - 运行 asyncio 循环和 tkinter gui
- javascript - 如何在点击时替换 8 张图片的部分 src?
- c# - RSocketClient 打印一些奇怪的消息
- r - R按因子水平对各列求和
- android - 启动 Xamarin.forms 应用程序时出错:尝试绘制太大(165514752 字节)位图
- python - 将变量名称作为原始字符串输入到python中的请求中
- php - 无法在 PHP 中接收从 Android 客户端发送的 JSON 数组