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

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


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

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 ]]


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




closed as off topic by quanta, Ladadadada, Khaled, Michael Hampton, mgorven Dec 27 '12 at 17:41

Questions on Server Fault are expected to relate to server, networking, or related infrastructure administration within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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

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

You can assign the output of the pipe to a variable

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

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

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"
  • @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. – Iain Dec 27 '12 at 15:26

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