Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a few .txt files (in the same directory) that look like this:

   123 carrot
    50 apple
    13 tomato
     5 potato
     2 pear


   100 carrot
    10 apple
     3 tomato
     2 potato

I need to merge them into one sorted list. So if I only had two lists above, I'd get

   223 carrot
    60 apple
    16 tomato
     7 potato
     2 pear

Is there an easy way to do this with shell commands, or should I start writing code?

Thank you!

share|improve this question
up vote 4 down vote accepted

Where is the line between "shell commands" and "code"? This example is perhaps beyond that line, but it is just a quick aggregation function in awk that I already had written for another (more elaborate) purpose, so I might as well post it.

Assuming the files are located in the directory dir/, awk could sum them as such:

awk '
    END { for (fruit in fruits) {printf "%6s %s\n", fruits[fruit], fruit} }
' dir/* | sort -rn


  • Check every line in all files and add the value of the first field to the existing value of the index of that fruit in the array fruits (or create that index if it does not exist).
  • When the files have been traversed, loop over the indices in fruits and print their value and their name in your specified format.
  • Array sorting in awk is possible, but it's a lot easier on the eye to just use sort. -rn sorts numerically in descending order.
share|improve this answer

You must log in to answer this question.

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