Categories
shellinfo tips

SORT – Sorting content of files

The ‘sort’ is a commonly used Linux command for sorting lines of text files.

Sorting a file in alphabetical order

sort filename.txt

This command will sort the contents of the ‘filename.txt’ file in alphabetical order and display it on the terminal.

Sorting a file in reverse alphabetical order

sort -r filename.txt

The ‘-r’ flag is used to reverse the order. So, this command will sort the contents of the ‘filename.txt’ file in reverse alphabetical order and display it on the terminal.

Sorting a file numerically

sort -n numbers.txt

If the file contains numbers, you can use the ‘-n’ flag to sort them numerically.

Sorting a file in reverse numerical order

sort -nr numbers.txt

This will sort the contents of the ‘numbers.txt’ file in reverse numerical order.

Sorting a file based on the second column

sort -k 2 filename.txt

If the file contains multiple columns or fields, you can sort based on a particular field by specifying the column number or character position using the ‘-k’ flag. In this example, the file will be sorted based on the second column.

Sorting a file based on a delimited field

sort -t , -k 2 filename.csv

If the file is comma-separated, you can specify the delimiter using the ‘-t’ flag. In this example, the file will be sorted based on the second column which is delimited by commas.

Sorting only unique lines from a file

sort -u filename.txt

You can use the ‘-u’ flag to sort only the unique lines from a file.

Sorting a file without considering case

sort -f filename.txt

The ‘-f’ flag can be used to sort a file without considering case.

Merging two sorted files

sort -m file1.txt file2.txt

You can merge two sorted files into one sorted file using the ‘-m’ flag.

Sorting files in a directory based on filename

ls | sort

You can sort the contents of a directory based on filename by piping the output of the ‘ls’ command to the ‘sort’ command.

Leave a Reply

Your email address will not be published. Required fields are marked *