2

I am trying to search for consecutive, repeated instances of numbers in a file, with each number on a different line. It's easiest to show what I mean in an example.

For example, my input would be:

16
16
8
8
16
16
4
8
8
8  

And my output would be:

16 2
8 2
16 2
4 1
8 3  

This may appear to be a duplicate, but though I have found many solutions (like this one) for finding the repetitions of a single character, none of them are able to search for multiple repeated characters.

  • Do you mean repeated characters (e.g. 111), repeated strings (e.g. 123123) or repeated lines? Will each line of your input only consist of a string of characters (including numbers) and no spaces? Do you just want repeated lines? – terdon Jan 19 at 18:16
  • @terdon - it was a badly worded title - I meant to put repeated lines. My question sort of changed as I was writing the post. I'll edit the title. – k-q-v Jan 19 at 18:25
7

You can use uniq to do this, though the standard format of its output is slightly different.

$ < in uniq -c
      2 16
      2 8
      2 16
      1 4
      3 8

Assuming in is a file that contains the input, you'll get what you see above.

  • which could be piped through awk '{print $2,$1}' for a quick'n'dirty way to get output in the order shown by the OP – steeldriver Jan 19 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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