Linux 如何使用grep/awk跨多行进行聚合平均?
假设我有一堆具有以下模式的文件: 文件1:Linux 如何使用grep/awk跨多行进行聚合平均?,linux,shell,awk,grep,find,Linux,Shell,Awk,Grep,Find,假设我有一堆具有以下模式的文件: 文件1: head1 random words number=100 random words ... head2 random words number=200 random words ... head1 random words number=200 random words ... 文件2: head1 random words number=1000 random words ... head2 rando
head1
random words
number=100
random words
...
head2
random words
number=200
random words
...
head1
random words
number=200
random words
...
文件2:
head1
random words
number=1000
random words
...
head2
random words
number=200
random words
...
head1
random words
number=2000
random words
...
我想看看在标题1下哪个文件的平均数字更大,在本例中,文件1的(100+200)/2=150
,而文件2的(1000+2000)/2=1500
所以我想以任何格式打印这个结果,但其中一种可能是:
File 1: 150
File 2: 1500
我对linux命令很陌生,有人能帮我解决这个问题吗?script
输出3个文件
解释
1) 使用foreach x(file1 file2 file3)
2) 打印不带行尾的文件名echo-n$x:“
3) 仅包含原始文件的相关部分
sed-n'/head1/,/\.\.\.\./p'$x|\
(sed-n
silent,/first str/,/second str/p
在两个字符串之间,$x
循环中的文件名)
4) 将字段分隔符设置为“=”awk-F“=”
,如果行在“=”car/number/{sum=sum+$2;cnt+}之后包含number inc cnt和sum值,则设置sum和count以计算平均值开始{sum=0;cnt=0}
5) 检查是否存在要求和的数字,是否存在打印平均值else打印0END{if(cnt)打印“sum/cnt;else打印“sum}”
输入文件
文件1:100+200=300/2=150
head1
random words
number=100
random words
...
head2
random words
number=200
random words
...
head1
random words
number=200
random words
...
head1
random words
number=1000
random words
...
head1
random words
number=2000
random words
...
head1
random words
number=3000
random words
...
head3
random words
number=200
random words
...
head4
random words
number=200
random words
...
head5
random words
number=500
random words
...
文件2:1000+2000+3000=6000/3=2000
head1
random words
number=100
random words
...
head2
random words
number=200
random words
...
head1
random words
number=200
random words
...
head1
random words
number=1000
random words
...
head1
random words
number=2000
random words
...
head1
random words
number=3000
random words
...
head3
random words
number=200
random words
...
head4
random words
number=200
random words
...
head5
random words
number=500
random words
...
文件3:无头1->0
head1
random words
number=100
random words
...
head2
random words
number=200
random words
...
head1
random words
number=200
random words
...
head1
random words
number=1000
random words
...
head1
random words
number=2000
random words
...
head1
random words
number=3000
random words
...
head3
random words
number=200
random words
...
head4
random words
number=200
random words
...
head5
random words
number=500
random words
...
grep用于查找文本,而不是像算术运算那样进一步处理文本。。。为此使用awk(),您的是“如何从多行记录中提取内容”和“如何从提取的值中计算平均值”的组合副本。在Awk中,这两种方法都很容易做到,并且基本上应该使用一行或两行。寻求解决这两个问题的办法;有很多。可能重复的可能重复的似乎与标题不相关。使用awk'$1==“number”{sum+=$2}END{print sum}FS==input file
可以获得大部分的效果,虽然sed
脚本显然很容易避免,但循环中的部分并不十分有用;但是temp文件和csh的使用极其可疑。