-1

i have a file with the following lines:

ex.

host1   169.254.228.92
host2   169.254.230.182
host3   169.254.163.79

and i want to sort it ascending by 3 column first and then 4

when im using :

sort -n -t .  -k 3,3  -k 4,4 test.txt 

it does not work properly, it only sorts by 3 column :

host13  169.254.10.154
host12  169.254.18.77
host14  169.254.74.233

Any solution ?

sopek96
  • 11
  • 1
  • 3
    looks like it's sorted properly. what did you expect to get? – karakfa Oct 10 '18 at 20:02
  • You need to have more than one IP like 169.254.10.* to see the effects of sorting by the 4th column. – glenn jackman Oct 10 '18 at 20:14
  • [Sort unique IP address in from Apache log](https://stackoverflow.com/q/18682308/608639), [Need to sort ips in Apache log file](https://stackoverflow.com/q/50053308/608639), [Sorting IP address according to the second field in file](https://unix.stackexchange.com/q/71704/56041), etc. – jww Oct 11 '18 at 04:24

2 Answers2

1

Try this:

sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 test.txt 

Sort first by the first field, and only the first field (-k 1,1), then by the second and only the second (-k 2,2), and so on (-k 3,3 -k 4,4).

Or just use sort -V.

soft87
  • 482
  • 2
  • 16
0

use map and a lambda function to sort a list of tuples

myDict = [{'from': '10.246.47.121' },{'from': '10.60.0.111'}, {'from': '192.168.156.113'}, {'from': '192.168.20.100'}]

def store_dict(myDict):
    myDict_by_ip = {"from":[]}
    for d in myDict:
        elements=d["from"].split(".")
        ip = [('element1',int(elements[0])),('element2',int(elements[1])),('element3',int(elements[2])),('element4',int(elements[3]))]    
        myDict_by_ip["from"].append(ip)
    return myDict_by_ip

myDict_by_ip = store_dict(myDict)

def sort_array(arr):
    return sorted(arr, key=lambda x: (x[0],x[1],x[2],x[3]),reverse=False)

result=list(map(lambda x:x,sort_array(myDict_by_ip['from'])))
data=[]
for components in result:
    ip=[]
    for key,value in components:
        ip.append(str(value))
    ip_string='.'.join(ip)
    data.append(ip_string)
print(data)
Golden Lion
  • 3,840
  • 2
  • 26
  • 35