Tony
Tony

Reputation: 2929

How to number the lines according to a field with awk?

I wonder whether there is a way using awk to number the lines according to a field. For example,

Input

2334 332
2334 546
2334 675
7890 222
7890 134
234  45
.
.
.

Based on the 1st field, I would have the following output

Output

1 2334 332
1 2334 546
1 2334 675
2 7890 222
2 7890 134
3 234  45
.
.
.

I would be grateful for your help.

Cheers,

T

Upvotes: 0

Views: 123

Answers (2)

ghostdog74
ghostdog74

Reputation: 342649

here's how,

awk '!a[$1]++{c++}{print c, $0}' file
1 2334 332
1 2334 546
1 2334 675
2 7890 222
2 7890 134
3 234  45

Upvotes: 2

Ben Jackson
Ben Jackson

Reputation: 93860

awk 'last != $1 { line = line + 1 } { last = $1; print line, $0 }'

Upvotes: 1

Related Questions