2

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
  • 1
    Googling wasn’t successful ;-). What about trying to figure something out yourself? – Stephen Kitt Jun 21 '17 at 11:28
8

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
3

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.