2

I'm trying to find most common word sorted alphabetically. For example:

  2 went
  2 wonder
  2 wont
  3 began
  3 little
  3 moment
  3 rabbit
  3 thing
  3 till
  4 alice
  4 bottle
  4 came
  4 sure
  4 window

The output should be alice (has highest value and it is the first word alphabetically).

I'm doing sort -nr and can't figure out what to do next.

1
  • Is that your source data, or the desired output? Apr 14, 2019 at 21:36

2 Answers 2

7

To sort by two fields, you need to tell sort what they are, and how to sort them; for example:

sort -k1,1nr -k2b < input

sorts by field 1 (-k1,1) numerically in reverse (descending) order; for lines where field 1 is equal, secondarily sort by the rest of the line (-k2) normally (lexically) not including the leading blanks (the spacing between the first and second field) in the sort key (b). The output on your sample input is:

  4 alice
  4 bottle
  4 came
  4 sure
  4 window
  3 began
  3 little
  3 moment
  3 rabbit
  3 thing
  3 till
  2 went
  2 wonder
  2 wont
0
0

Though Jeff already answered your question using only sort, I thought I'd post my approach anyway. I didn't know about sort's ability to sort by two fields, so I used it merely for "pre"-sorting you input. Since the words are ordered Z-A in every section, we just need to reverse their order. For this, I'm using awk:

sort -r file | awk '{if($1==x){var=$0"\n"var} else{print var;var=$0;x=$1}} END{print var}' | grep -v ^$

The grep -v ^$ is only there to remove the first line of awk's output, which is empty.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .