I have file file.txt
which look like this
a
b
b
c
c
c
I want to know the command to which get file.txt
as input and produces the output
a 1
b 2
c 3
I have file file.txt
which look like this
a
b
b
c
c
c
I want to know the command to which get file.txt
as input and produces the output
a 1
b 2
c 3
I think uniq
is the command you are looking for. The output of uniq -c
is a little different from your format, but this can be fixed easily.
$ uniq -c file.txt
1 a
2 b
3 c
If you want to count the occurrences you can use uniq
with -c
.
If the file is not sorted you have to use sort
first
$ sort file.txt | uniq -c
1 a
2 b
3 c
If you really need the line first followed by the count, swap the columns with awk
$ sort file.txt | uniq -c | awk '{ print $2 " " $1}'
a 1
b 2
c 3
You can use this awk:
awk '!seen[$0]++{ print $0, (++c) }' file
a 1
b 2
c 3
seen
is an array that holds only uniq items by incrementing to 1
first time an index is populated. In the action we are printing the record and an incrementing counter.
Update: Based on comment below if intent is to get a repeat count in 2nd column then use this awk command:
awk 'seen[$0]++{} END{ for (i in seen) print i, seen[i] }' file
a 1
b 2
c 3