Is possible for sort to sort 1 2 3 4..9 instead of 1 10 11 12.. 2 20

sort

I use this script for discover ip online

#!/bin/sh
set -e

# no args
if [ $# -lt 1 ]; then
    echo "Too few args"
    echo "Options are:"
    echo "-a: Tell me which host is online"
    echo "-b: show only list of ip found"
    exit 1
fi

# too many args
if [ $# -gt 1 ]; then
    echo "$1 option unknown"
    echo "Options are:"
    echo "-a: Tell me which host is online"
    echo "-b: show only list of ip found"
    exit 1
fi



case $1 in
-a)
array1=(
`nmap -sP 192.168.0.0/24 | awk '/is up/ {print up}; {gsub (/\(|\)/,""); up = $NF}'`
)
for i in ${array1[@]};do echo "Ip $i is online";done
;;
-b)
nmap -sP 192.168.0.0/24 | awk '/is up/ {print up}; {gsub (/\(|\)/,""); up = $NF}'|sort -fn
;;
*)
    echo "$1 option unknown"
    echo "Options are:"
    echo "-a: Tell me which host is online"
    echo "-b: show only list of ip found"
;;
esac

but using -b return a list like this

192.168.0.1
192.168.0.11
192.168.0.14
192.168.0.15
192.168.0.17
192.168.0.2
192.168.0.3
192.168.0.44
192.168.0.46
192.168.0.49
192.168.0.50

i want list sort like this

    192.168.0.1
    192.168.0.2
    192.168.0.3
    192.168.0.11
    192.168.0.14
    192.168.0.15
    192.168.0.22
    192.168.0.44
    192.168.0.46
    192.168.0.49
    192.168.0.50

Any suggestion for sort?

Best Answer

sort according to the . separated 4th field only by:

... | sort -t. -k4,4n
  • -t. sets the input field delimiter as .

  • --k4,4n sorts the file according to the 4th field only, and n implements numeric sorting

Example:

$ cat file.txt
192.168.0.1
192.168.0.11
192.168.0.14
192.168.0.15
192.168.0.17
192.168.0.2
192.168.0.3
192.168.0.44
192.168.0.46
192.168.0.49
192.168.0.50

$ sort -t. -k4,4n file.txt
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.11
192.168.0.14
192.168.0.15
192.168.0.17
192.168.0.44
192.168.0.46
192.168.0.49
192.168.0.50