easy way to change the uniq -c output?
Asked Answered
L

2

7

I have a simple file like this:

Term1 column2 column3
Term2 column2 column3
Term3 column2 column3
Term2 column2 column3
Term1 column2 column3
Term2 column2 column3

If I sort on the first column and get a count for the terms:

cut -f1 -d ' ' file | sort | uniq -c

The results shows me this:

    2 Term1
    3 Term2
    1 Term3

But I would rather see this:

Term1 2
Term2 3
Term3 1

Is there an easy way to "change" the uniq output to do this or would i still need to pipe the output to sed or awk to get this?

This seems a simple question so my apologies if this was asked before.

Labyrinthodont answered 17/10, 2017 at 10:3 Comment(1)
Please use code tags for Input samples rather than quote tags.Porphyry
T
5

Uniq doesn't give the option to rearrange output.

You can do this using awk :

cut -f1 -d ' ' file | sort | uniq -c | awk '{print $2, $1}'

Term1 2
Term2 3
Term3 1

Or using awk and then sort (recommended)

$awk '{a[$1]++} END{for (i in a) print i,a[i] }' file | sort -k1
Term1 2
Term2 3
Term3 1
Tepee answered 17/10, 2017 at 10:6 Comment(5)
awk one-liner won't guarantee the sorted output. (i in a)Debor
-k1 is redundant.Womanly
@karakfa: Can you elaborate ?Tepee
sort -k1 is the default behavior of sort, no need to explicitly specify. Unless you meant -k1,1Womanly
@karakfa: Oh okay.Tepee
M
2

The shortest one with GNU datamash tool:

datamash -Ws -g1 count 1 <file

The output:

Term1   2
Term2   3
Term3   1
Metabolite answered 17/10, 2017 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.