Sort

From Wiki
Jump to navigation Jump to search

By default, sorts file rows using the first field as key, assuming fields are separated by white space.

To sort in reverse numerical order:

sort -nr <file>

To sort on first two fields using : as delimeter:

sort -t: +0 -2 <file>

To sort on characters 20-25:

sort +0.20 -.25 <file>

To merge file1 and file2:

sort -m <file1> <file2>

To merge file 1 with the output of ls:

ls | sort -m file1 -

To sort the password file by id:

sort -t: -k3 -n /etc/passwd

To extract usernames (play with the head and tail):

sort -t: -k3 -n /etc/passwd | tail -18 | head -17 | awk -F: '{print $1}'

To shuffle lines randomly:

sort -R myfile.txt

To sort IP addresses:

sort -t. -k1,1n -k2,2n -k3,3n -k4,4n myfile.txt