bash Linux 连续行之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22348603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linux differences between consecutive lines
提问by SYNCRo
I need to loop trough n
lines of a file and for any i between 1 and n - 1
to get the difference line(n - 1) - line(n)
.
我需要循环n
一个文件的低谷行和任何一个i between 1 and n - 1
以获得差异line(n - 1) - line(n)
。
And here is the source file:
这是源文件:
root@syncro:/var/www# cat cron.log | grep "/dev/vda"
/dev/vda 20418M 14799M 4595M 77% /
/dev/vda 20418M 14822M 4572M 77% /
/dev/vda 20418M 14846M 4548M 77% /
/dev/vda 20418M 14867M 4527M 77% /
/dev/vda 20418M 14888M 4506M 77% /
/dev/vda 20418M 14910M 4484M 77% /
/dev/vda 20418M 14935M 4459M 78% /
/dev/vda 20418M 14953M 4441M 78% /
/dev/vda 20418M 14974M 4420M 78% /
/dev/vda 20418M 15017M 4377M 78% /
/dev/vda 20418M 15038M 4356M 78% /
root@syncro:/var/www# cat cron.log | grep "/dev/vda" | cut -b 36-42 | tr -d " M"
4595
4572
4548
4527
4506
4484
4459
4441
4420
4377
4356
those /dev/vda...
lines are logged hourly with df -BM
in cron.log
file and the difference between lines will reveal the hourly disk consumption.
这些/dev/vda...
线以每小时记录df -BM
在cron.log
文件和行之间的差别将揭示每小时磁盘消耗。
So, the expected output will be:
因此,预期的输出将是:
23 (4595 - 4572)
24 (4572 - 4548)
...
43 (4420 - 4377)
21 (4377 - 4356)
I don't need the text between (
and )
, I put it here for explanation only.
我不需要的文本(
和)
,我把它放在这里仅用于说明。
回答by hek2mgl
I'm not sure if I got you correctly, but the following awk
script should work:
我不确定我是否正确理解,但以下awk
脚本应该可以工作:
awk '{if(NR>1){print _n-};_n=}' your.file
Output:
输出:
23
24
21
21
22
25
18
21
43
21
You don't needthe other programs in the pipe. Just:
您不需要管道中的其他程序。只是:
awk '/\/dev\/vda/ {if(c++>0){print _n-};_n=}' src/checkout-plugin/a.txt
will be enough. The regex on start of the awk
scripts tells awk to apply the following block only to lines which match the pattern. A side effect is that NR
can't be used anymore to detect the "second line" in which the calculation starts. I introduced a custome counter c
for that purpose.
就足够了。awk
脚本开始时的正则表达式告诉 awk 将以下块仅应用于匹配模式的行。一个副作用是NR
不能再用于检测计算开始的“第二行”。c
为此,我引入了一个客户柜台。
Also note that awk
will remove the M
on it's own, because the column has been used in a numeric calculation.
另请注意,awk
将M
自行删除,因为该列已用于数值计算。