count unique ip addresses in unix hosts file

Posted on 2008-11-13
Last Modified: 2013-12-26
hi unix gurus!!!
im stumped on a simple solution for this.
for an/etc/hosts file that contains entries in format:
IPAddress <space> Hostname <newline>

Example: localhost webserver

what would be the simplest way to COUNT the number of UNIQUE IPAddresses in a single piped command?

Question by:J P
    LVL 19

    Accepted Solution

    something like;
       cat /etc/hosts | awk '{print $1}' | sort -n | uniq | wc -l
    LVL 19

    Assisted Solution

    or :-)
      cat /etc/hosts | grep -v "^#" | grep -v "^$" | awk '{print $1}' | sort -n | uniq | wc -l
    LVL 40

    Assisted Solution


     cat /etc/hosts | grep -v '^#' | awk '{ print $1 } ' | sort | uniq -c
    LVL 6

    Author Closing Comment

    by:J P
    thanks you all for prompt help !!!
    LVL 48

    Expert Comment

    Or a shorter solution is

    awk '/^[0-9]/ {print $1}' /etc/hosts | sort -u | wc -l

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Attention: This article will no longer be maintained. If you have any questions, please feel free to mail me. Please see for the updated article. It is avail…
    I promised to write further about my project, and here I am.  First, I needed to setup the Primary Server.  You can read how in this article: Setup FreeBSD Server with full HDD encryption (…
    Learn how to get help with Linux/Unix bash shell commands. Use help to read help documents for built in bash shell commands.: Use man to interface with the online reference manuals for shell commands.: Use man to search man pages for unknown command…
    This tutorial goes over how to archive and restore FreeBSD jails that are managed by ezjail.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now