0

Am facing one small issue with command trace where I am trying to find average and getting it but I need output without decimal point. Below is the sample command which is trying to read from a file with few grep conditions.

grep "#COMPLETE#" Requestlog1.log | grep "#O#" | awk -F"#" '{ sum += $NF; n++ } END { if (n > 0) print sum / n; }'

Am getting output 672.714

Actual answer should be rounded off to 673

4
  • post the initial Requestlog1.log fragment – RomanPerekhrest May 24 '18 at 10:38
  • i dint get you?, its a file am trying to get the output from it – Irfan May 24 '18 at 10:41
  • your pipeline is redundant, that's why I asked to post Requestlog1.log fragment. You can obtain an optimized solution here (in case if you are interested in such one) – RomanPerekhrest May 24 '18 at 10:48
  • 1
    I'd suggest a clearer title, since the body says "round 672.714 (up) to 673" while the title says "remove decimal..." – Jeff Schaller May 24 '18 at 11:22
0

There isn't any ceil function in awk, but you can define one:

... | awk -F"#" 'function ceil(x){return (x == int(x)) ? x : int(x)+1} { sum += $NF; n++ } END { if (n > 0) print ceil(sum / n); }'

Note that int() rounds like would do floor in other languages.

Credits: here

3
  • @Irfan I'm glad to help. If you find the answer useful, consider upvoting and/or accepting the answer ;-) – oliv May 24 '18 at 11:15
  • int() is equal to floor() only for positive numbers, not for negative ones. – Isaac May 24 '18 at 11:56
  • I need one more help on this, could you please help me out to paste the output of this in excel sheet, wil be helpfull if someone helps – Irfan Jul 3 '18 at 15:34
1

You can replace your print with printf "%.0f\n". Also note that awk can do grep's job:

awk -F"#" '
  /#COMPLETE#/ && /#O#/ {sum += $NF; n++}
  END {if (n > 0) printf "%.0f\n", sum / n}'

It rounds to the nearest integer (x.3 to x, x.7 to x+1 (x-1 for negative numbers), x.5 to x or x+1 (x-1 for negative numbers) depending on whether x is even or odd)

4
  • Hi..i need help in above linux sentence, If ther is no value am getting empty variable is it possible to set as default 0 if ther is no value to post? – Irfan Sep 3 '18 at 14:01
  • @Irfan, add a ;else print 0 in the END statement – Stéphane Chazelas Sep 3 '18 at 14:03
  • plz help me with this command. where to put else print 0 '{if(max<$NF){max=$NF;line=$NF}}END{print line}' – Irfan Sep 3 '18 at 14:20
  • got it..it worked:) – Irfan Sep 3 '18 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.