Question

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).

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.

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.

Was it helpful?

Solution

I'm not sure if I got you correctly, but the following awk script should work:

awk '{if(NR>1){print _n-$4};_n=$4}' your.file

Output:

23
24
21
21
22
25
18
21
43
21

You don't need the other programs in the pipe. Just:

awk '/\/dev\/vda/ {if(c++>0){print _n-$4};_n=$4}' 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.

Also note that awk will remove the M on it's own, because the column has been used in a numeric calculation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top