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 biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

adding numbers in various files and sending total to other files 1

Status
Not open for further replies.

bi

Technical User
Apr 13, 2001
1,552
US
My scripting abilities are limited. I'm trying to learn. I am grateful for any ideas and help.

I have a group of files (file1.num, file2.num, etc.) that have numbers in them that I need to add and send the total for each individual file to a particular line in another file (file1.num.total, file2.num.total, etc.).

To get the total of the numbers in one of the files, I use this:

typeset -i i
i=0
while read -r j
do
i=i+j
done < file1.num
echo $1 > file1.num.total

How can I script it so I can have all the *.num files processed at the same time?
 
Hi,
If I understand what you are asking correctly then this should work. This is untested.

for filename in *.num
do
typeset -i i
i=0
while read -r j
do
i=i+j
done < ${filename}
echo $1 > ${filename}.total
done
 
awk '{sum[FILENAME]+=$1} END {for(file in sum) print file, sum[file] > file&quot;.total&quot;}' *.num
 
butterfm, yep. that works great. Thanks.

Ygor, yours works, but I have 76 files to work on and I get an error: &quot;too many output files 10&quot; and only 10 of the files are created.

I tried it using nawk and get this error:
nawk: syntax error at source line 1
context is
{sum[FILENAME]+=$1} END {for (file in sum) print file, sum[file] > >>> file&quot;.total&quot; <<<
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top