Introduction
While working on data in Linux Operating system, it’s very important to know how to sort columns efficiently. Like workin on log files, organizing table data, or fetching specific information, sorting columns helps you understand your data fast. In this article, we’ll explore different methods to sort columns under Linux using the Bash shell’s options. ALWAY MAKE SURE YOU BACKUP YOUR DATA FIRST AND THEN WORK ON BACKUP COPY.
Using “sort” command:
The sort command is a versatile tool for processing the data in Linux. It offers various options to customize your sorting experience. For sorting columns, simply pipe the data into the command and specify the column number to sort, as below, lets take an example of “/etc/passwd” file by backing it up under other directory like /tmp.
Example:
$ cat passwd |sort -k 2 |
Here, command sorts the contents based on the second column.
Using awk command:
awk is a very powerful tool which gives options to process text files. Hence sorting columns is easy with this utility. Here is an example.
$ awk ‘{print $2, $1}’ passwd | sort |
Command prints the second and first columns of ‘data.txt’ and sorts the output by the first column.
Using cut command:
In order to sort mentioned column without displaying the entire row, you can combine the cut and sort commands. Here’s an example:
$ cut -d’,’ -f2 passwd | sort |
Above command uses the “cut” with second column and comma as a separator.
Using csvsort command:
If you want to sort CSV files, csvsort tool can be a right fit for you. It can be used to sort CSV files based on column values. Use the following syntax:
$ csvsort -c 2 data.csv |
Above command is to sort the data.csv file by the second column.
Summary:
Ability to sort column in Linux is a valuable asset which enables your data processing skills. The utilities like sort along with awk, cut, and csvsort, gives powerful options for efficiently sort with column. By aquring these methods, you will be able to process and manage data more effectively in Linux. Hence try these methods by backing up your data first and then working on copies and unleash the power of column sorting in Linux!