0

I have a file that contains something like the following:

red dog  
red cat  
red bird  
red horse  
blue hamster  
blue monkey  
blue lion  
pink pony  
pink whale  
pink pig  
pink dolphin 

I need to increment a counter for every color, and then for every animal. So red would be 1, blue 2, pink 3. Next, dog, cat, bird, and horse would be 1, 2, 3, and 4. I need hamster to begin at 1 again because we are starting a new color.

If I do a "while read color animal" of said file, what can I do to compare when color is no longer equal to the previous color?

I am looking for something like this:

1.1  
1.2  
1.3  
1.4  
2.1  
2.2  
2.3  
3.1  
3.2  
3.3  
3.4  

Any suggestions would be greatly appreciated :)

1

Something like this with awk:

$ awk '$1 != c { cc++; c=$1; ac=0; a="" } $2 != a { ac++; a=$2 } { printf("%d.%d\n", cc, ac) }' file
1.1
1.2
1.3
1.4
2.1
2.2
2.3
3.1
3.2
3.3
3.4

The awk script keeps track of four things:

  1. The most recently read animal name, a.
  2. The most recently read colour, c.
  3. The "animal counter", ac.
  4. The "colour counter", cc.

It updates these variables depending on what's found in the two columns of input.

  • If the colour is not the same as what's most recently read, increment cc and remember this colour instead. Also reset ac and a.
  • If the animal is not the same as what's most recently read, increment ac and remember this animal instead.

Then print cc and ac for each line of input.

If the animals on each line is guaranteed to be unique, one could get rid of the a variable.

0
perl -pale '$_ = join ".", reverse ++$h{$F[0]}, scalar keys %h'

The hash %h holds keyA => count and scalar keys %h returns the number of keys at any point in time. Then we reverse the result and join them with a comma.

Result

1.1
1.2
1.3
1.4
2.1
2.2
2.3
3.1
3.2
3.3
3.4

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.