4

I know this should be an easy one by googling but was not successful. Sorry for that.

I would like to print the first line of groups defined the value in the first column. Delimiter is tab.

Input:

A 5
A 3
B 2
B 1
B 77
C 4
C 10000
D 99

Output:

A 5
B 2
C 4
D 99
Rob
  • 1,780
Michael
  • 193

3 Answers3

9

The shortest one:

awk -F'\t' '!a[$1]++' file

The output:

A   5
B   2
C   4
D   99

  • !a[$1]++ - ensures line printing on encountering the first unique value of the 1st column
4

Something like can do the work:

awk -F\t 'BEGIN {A=""} {if ($1!=A) { print $0; A=$1}}' input_file

When you initialize variable A select initial value which is not in to the list of existing in column 1

Romeo Ninov
  • 17,484
2

Here are two non-awk options:

sort u foo -k 1,1

Use sort purely for the -u (--unique) capability. Use only the first character (-k 1,1) for comparison.

rev foo | uniq -f 1 | rev

Use uniq. The -f option only allows specifying a start field for comparison, so we use some legerdemain to first reverse (rev) the input before uniq, and then rev that output again.

gardenhead
  • 2,017