2

Here is some lines of my input file:

  08:51:36 UN 127.0.0.1
  08:51:36 UN 127.0.0.2
  08:51:36 UN 127.0.0.3
  08:53:50 DN 127.0.0.1
  08:53:50 DN 127.0.0.2
  08:53:50 DN 127.0.0.3

I want to write a shell script which has as input the ip address

 ./CountRate.sh 127.0.0.1

This script have to return 0.5. The formula is: The number of times that the node with IP 127.0.0.1 have the status UN which is "1" DIVIDED BY the number of lines on which appear 127.0.0.1 which is "2". What Linux commands I have to use to achieve this?

  • Is the answer “1/2”, “0”, or “0.5”, or “0.500”, or? – Jeff Schaller Jul 11 '18 at 11:14
  • @JeffSchaller 0.5 – user1543915 Jul 11 '18 at 11:23
  • 4
    This seems to be posed suspiciously like a homework problem. – Ian MacDonald Jul 11 '18 at 13:54
1

The below script uses two parameters: (IP address and input-file name)

#!/bin/bash

echo "IP address: $1"
echo "Input file name: $2"

Count_IP=$(grep -c "$1" "$2" )
Count_IP_UN=$(grep "$1" "$2" |grep -c "UN")

echo "IP Count: $Count_IP"
echo "IP Count with UN: $Count_IP_UN"

Result=$(bc <<< "scale=1; $Count_IP_UN/$Count_IP"| awk '{printf "%0.1f", $0}')
echo "The result is: $Result"

Execution example:

$ ./CountRate.sh 127.0.0.1 inp.txt 
IP address: 127.0.0.1
Input file name: inp.txt
IP Count: 2
IP Count with UN: 1
The result is: 0.5
  • 2
    This scans through the whole file twice for no reason. I'd recommend the awk answer instead. – NieDzejkob Jul 11 '18 at 12:10
9

The awk scripting language can easily do this:

awk -v host=127.0.0.1 '
  $3 == host {n++; x += $2 == "UN" ? 1 : 0} 
  END {print x/n}
' inputfile
0.5
  • I think when something evaluates to a boolean in awk, it's 1 or 0 like C. That means that you can omit the ? 1 : 0, and get the same result. – JoL Jul 11 '18 at 15:20

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.