Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting unique by column - sort command?

I have this file:

hello 1
hello 2
world 1
world 2
hello 3
hi    3
hi    4

I want to sort this like so,

hello 1
hi  3
world 1

The thing is I need only the first unique item in column 1.

I tried sort -k1 -u file.txt but it isn't working as I expect. How do I go about this?

like image 409
ComputerFellow Avatar asked Aug 21 '13 09:08

ComputerFellow


People also ask

What is sort unique?

What are sort and uniq? Ordering and manipulating data in Linux-based text files can be carried out using the sort and uniq utilities. The sort command orders a list of items both alphabetically and numerically, whereas the uniq command removes adjacent duplicate lines in a list.

How do I sort the second column in Unix?

Use the -k option to sort on a certain column. For example, use " -k 2 " to sort on the second column. In old versions of sort, the +1 option made the program sort on the second column of data ( +2 for the third, etc.).

Which command is used to sort?

The sort command is used in Linux to print the output of a file in given order. This command processes on your data (the content of the file or output of any command) and reorders it in the specified way, which helps us to read the data efficiently.

How do I sort specific columns in Linux?

Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.


2 Answers

This might work for you:

sort -uk1,1 file

This sorts the file on the first field only and removes duplicate lines based on the first field.

like image 160
potong Avatar answered Sep 19 '22 04:09

potong


Sort and give unique list based on column 1

sort -u -t : -k 1,1 test.txt

-t : = colon is separator

-k 1,1 = based on column 1

Sort and give unique list based on column 1 & column 3

sort -u -t : -k 1,1 -k 3,3 test.txt

-t : = colon is separator

-k 1,1 3,3 = based on column 1 & column 3

like image 24
Prakash Avatar answered Sep 20 '22 04:09

Prakash