0

I have a directory full of plain text files that have tags on the first line, and I want to get a list of the tags and their frequency. I've extracted the tags and sorted them into a big list; let's say it looks like this:

apple
banana
banana
banana
banana
orange
orange
kumquat
pomegranate
pineapple
pineapple
pineapple

I then pipe it through uniq -c to transform it into a list with counts:

      1 apple
      4 banana
      2 orange
      1 kumquat
      1 pomegranate
      3 pineapple

I'd now like to sort it, first by number in reverse order (largest numbers first), and then in forwards alphabetical order. I try to do this by piping through sort -bnr (ignore leading whitespace, numerical sort, in reverse order), but the -r applies to the letter part as well:

      4 banana
      3 pineapple
      2 orange
      1 pomegranate
      1 kumquat
      1 apple

I thought about the -k option to sort by multiple fields, which I just learned about the other day, but it looks like the reversal can't be applied separately for different-k options (perhaps it just puts the output through tac or something?). Piping it through a second sort doesn't work because it ignores the previous sort and mixes up the numerical part again.

Ideally the solution would still use sort and uniq, but I'm open to switching to a different tool if necessary. This may end up in a script, though, so a solution requiring interactive tools is out.

0

Oops, found an answer already because I started randomly browsing items in the "related" sidebar! Turns out you can use parameters after field specifiers to apply them only to that field -- I read that part of the man page but evidently didn't read very carefully, because I missed:

OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which override global ordering options for that key. If no key is given, use the entire line as the key.

Final command:

sort -bk 1rn -k 2

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.