9

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?

ComputerFellow
  • 11,710
  • 12
  • 50
  • 61

3 Answers3

26

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.

potong
  • 55,640
  • 6
  • 51
  • 83
8

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

Prakash
  • 4,479
  • 30
  • 42
3

You can pipe it to awk:

sort -k1 file | awk '!($1 in a){a[$1]; print}'
hello 1
hi    3
world 1
anubhava
  • 761,203
  • 64
  • 569
  • 643