Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

find pattern and then sum specific column 1

Status
Not open for further replies.

ogniemi

Technical User
Nov 7, 2003
1,041
PL
(ksh).

input (only example):
c 111
c 222
c 111
b 100
c 333
b 111
b 222
r 100
c 100
r 200

get all lines having the same 1st column and then sum 2nd column

result:
b 433
c 877
r 300



thx in advance.
 
Hi

This is the easiest solved with [tt]awk[/tt]. By the way, there are dozens of solutions for this in forum271.
Code:
awk '{v[$1]+=$2}END{for(i in v)print i,v[i]}' /input/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].

Feherke.
 
Hi

By the way, it can also be solved with standard command-line tools :
Code:
cut -d ' ' -f 1 /input/file | sort -u | while read v; do echo -n "$v "; grep "^$v " /input/file | cut -d ' ' -f 2 | tr '\n' '+' | sed 's/+$/\n/' | bc; done
This works in (pd)[tt]ksh[/tt] too, but only tested with GNU tools.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top