Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

   123 carrot
    50 apple
    13 tomato
     5 potato
     2 pear

and

   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
add comment

1 Answer

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 '
    {fruits[$2]+=$1}
    END { for (fruit in fruits) {printf "%6s %s\n", fruits[fruit], fruit} }
' dir/* | sort -rn

Breakdown:

  • 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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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