Linux / Unix: Sort Specific Field or Column

Linux / Unix: Sort Specific Field or Column

To sort a specific field or column in a Linux or Unix shell, you can use the sort command with the -k option and a field specification to specify which field to sort on.

For example, to sort a file containing tab-separated values (TSV) by the second field, you can use the following command:

r‮fe‬er to:lautturi.com
sort -k2 file.tsv

This will sort the file in ascending order based on the values in the second field.

You can also use the -r option to sort the file in descending order. For example:

sort -r -k2 file.tsv

If you want to sort the file by multiple fields, you can specify additional -k options. For example, to sort the file first by the second field and then by the third field, you can use the following command:

sort -k2 -k3 file.tsv

You can also use the -t option to specify a different field separator, such as a comma for CSV files. For example:

sort -t, -k2 file.csv

Keep in mind that the sort command only works with plain text files. If you want to sort fields or columns in other types of files, such as Excel files, you will need to use a different tool or script.

Created Time:2017-10-29 22:08:59  Author:lautturi