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?
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.
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.).
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.
Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With