-3

I write the following syntax (exist in my ksh script) in order to find how many digits I have in IP address

IP_address=127.1.1.1
echo  $IP_address | sed s'/\./ /g' | wc | awk '{print $2}'
4

.

IP_address=127.1.1
echo  $IP_address | sed s'/\./ /g' | wc | awk '{print $2}'
3

Please advice how to improve my syntax to make it - simpler and shorter and faster? (prefer without echo command ) , we can use also perl or awk or sed etc

Example what I defined in my code

 if [[ ` echo  $IP_address | sed s'/\./ /g' | wc | awk '{print $2}' ` -eq 3 ]]
        then

             three_octat=true


             elif  [[ ` echo  $IP_address | sed s'/\./ /g' | wc | awk '{print $2}' ` -eq 4 ]]

    then

          three_octat=false

         fi
yael
  • 2,433
  • 5
  • 31
  • 43
  • You should be able to simplify that to a single piped expression: `echo $IP_address | awk -F. '{print NF}'` - essentially define awk's field separator (`-F`) as '`.`' and display (`print`) the number of fields (`NF`). – cyberx86 Dec 27 '12 at 10:07
  • You should probably use `tr` instead of `sed` if you just want to swap one character for another. – David Schwartz Dec 27 '12 at 11:37

1 Answers1

1

From the wc man page

-w, --words print the word counts

So you can get rid of the awk at the end of the pipe.

echo  $IP_address | sed s'/\./ /g' | wc -w
4

You can assign the output of the pipe to a variable

num_octets=$(echo  $IP_address | sed s'/\./ /g' | wc -w)
echo $num_octets
4

Now you have a variable containing the number of octets you can do whatever you want by just querying it e.g.

#!/bin/ksh
IP_address=127
num_octets=$(echo  $IP_address | sed s'/\./ /g' | wc -w)
case $num_octets in
  "1" )
        echo "1 Octet" ;;
  "2" )
        echo "2 Otets" ;;
  "3" )
        echo "3 Octets" ;;
  "4" )
        echo "4 Octets" ;;
   *)
        echo "Invalid IPv4 Address"
esac
user9517
  • 115,471
  • 20
  • 215
  • 297
  • @Lain its not work properly because wc –w output print the number with space so case not read the integer numbers ( try it ) , any way my target was to find other solution without use echo command , – yael Dec 27 '12 at 11:01
  • @yael: Not on my system but easily fixed and left as an exercise for you. – user9517 Dec 27 '12 at 15:26