Matt Philips
Matt Philips

Reputation: 25

Linux, awk and how to count and print consecutive lines in a file?

For example I have a file like:

  apple
  apple
  strawberry

What I want to achieve is to print the consecutive line(apple) and count how many times it is consecutive(2) like this: apple-2 using awk.

My code so far is this however it does the following: apple1-apple1.

awk '{current = $NF;
getline;
if($NF == current) i++; 
printf ("%s-%d",current,i) }' $file

Thank you in advance.

Upvotes: 0

Views: 504

Answers (2)

dawg
dawg

Reputation: 103754

Given:

$ cat file
apple
apple
strawberry
mango
apple
strawberry
strawberry
strawberry

You can do:

$ awk '$1==last{seen[$1]++} 
               {last=$1}
       END{for (e in seen) 
            print seen[e]+1, e}' file
2 apple
3 strawberry

Upvotes: 0

James Brown
James Brown

Reputation: 37394

How about uniq -c and awk for filtering:

$ uniq -c foo|awk '$1>1'
      2   apple

Upvotes: 1

Related Questions