1

Intake file

website1 ip 20 website1 ip 30 website1 ip 10 website2 ip 200 website2 ip 10 website3 ip 150 

I need it to sort so that the sum of the 3rd with the associated website will show first with the highest total with the website

website2 has 210 website 3 has 150 website1 has 60

website2 ip 200 website2 ip 10 website3 ip 150 website1 ip 30 website1 ip 20 website1 ip 10 

ive tried sort -k3n -k1n but that is not the results i am looking for 230 website2 ip 200

1
  • You probably won't find a "pure" sort solution. sort compares on a line-by-line basis but your sorting criteria depends on sorting in groups, then lines. Commented Nov 22, 2016 at 20:33

1 Answer 1

3

You can use awk to have 2 pass and sum the column 3 per website (column 1) and append a new column in the output. Then sort using new column in output and finally strip first column from output using cut:

awk 'FNR==NR{sum[$1]+=$3; next} {print sum[$1] "\t" $0}' file file | sort -k1nr -k4nr | cut -f2- website2 ip 200 website2 ip 10 website3 ip 150 website1 ip 30 website1 ip 20 website1 ip 10 

Output of awk command:

awk 'FNR==NR{sum[$1]+=$3; next} {print sum[$1] "\t" $0}' file file 60 website1 ip 20 60 website1 ip 30 60 website1 ip 10 210 website2 ip 200 210 website2 ip 10 150 website3 ip 150 
Sign up to request clarification or add additional context in comments.

10 Comments

Hey @anubhava thanks for the help! , it is sorting by the sum of hte first column but it is not putting the 4th column in order
You can also try this command: awk 'FNR==NR{sum[$1]+=$3; next} {print sum[$1] "\t" $0}' file file | sort -k1nr -k4nr | cut -f2-
ahhhh I know what the problem is. my raw text file isn't as perfect as my example. there is 2 spaces between the IP and the count so it doesnt work. I just need to clean it up and it works !
Actually thats not the problem so why is it it will sort website1,website2,website3 but not real websites.....
If you can provide me a sample of your actual data on pastebin.com then I can surely look into that.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.