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
share|improve this question
    
Googling wasn’t successful ;-). What about trying to figure something out yourself? – Stephen Kitt yesterday
up vote 6 down vote accepted

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
share|improve this answer
    
    
@Archemar, indeed, the shortest one ) – RomanPerekhrest yesterday

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

share|improve this answer
    
it should be -F'\t', with -F\t it outputs all lines for me. ibb.co/bZaMNk – RomanPerekhrest yesterday

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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