Get the average of lines with the same first 4 letters


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Get the average of lines with the same first 4 letters
# 1  
Old 08-14-2018
Get the average of lines with the same first 4 letters

How to sum up and print into the next line the total SUM.
Code:
]$ cat hhhh
aaa1a 1
aaa1g 2
aaa1f 3
baa4f 3
baa4d 4
baa4s 4
cddg1 3
cddg3 4
cddfg 1

$ cat hhhh|awk ' {sum+=$2} END {print sum}'
25

Desire output:
Code:
aaa1a 1
aaa1g 2
aaa1f 3

Total Sum of aaa1: 6

=======================
baa4f 3
baa4d 4
baa4s 4
 
Total Sum of baa4: 11

=======================
cddg1 3
cddg3 4
cddfg 1
Total Sum of cddg: 8

# 2  
Old 08-14-2018
You might try something like:
Code:
awk '
function print_total() {
	printf("\nTotal Sum of %s: %d\n", last, total)
}
last != substr($1, 1, 4) {
	if(NR > 1) {
		print_total()
		printf("\n=======================\n")
	}
	last = substr($1, 1, 4)
	total = 0
}
{	print
	total += $2
}
END {	print_total()
}' hhhh

but, with the sample data you provided, I get the output:
Code:
aaa1a 1
aaa1g 2
aaa1f 3

Total Sum of aaa1: 6

=======================
baa4f 3
baa4d 4
baa4s 4

Total Sum of baa4: 11

=======================
cddg1 3
cddg3 4

Total Sum of cddg: 7

=======================
cddfg 1

Total Sum of cddf: 1

instead of what you said you wanted. The output above seems to more correctly match the title of this thread. If this isn't what you really wanted, please explain your requirements more clearly.

You should always tell us what operating system and shell you're using when you start a new thread. Otherwise, suggestions you receive might not work in your environment. In this case, if you're using a Solaris/SunOS operating system, change awk in the above suggestion to /usr/xpg4/bin/awk or nawk.

Note that using cat as you did in your sample code, eats up system resources and makes your code slower than letting awk read the file directly (as I did in my suggestion above).
This User Gave Thanks to Don Cragun For This Post:
# 3  
Old 08-15-2018
Thank you Don, my question also.. Is there a way to 1 liner that? In one liner. ii understand it more easily and i can able to repeat it someday.
Thank you

------ Post updated at 07:39 AM ------

Also if you can one liner please do, if not.. can you please explain each line? put comment on them please?
# 4  
Old 08-15-2018
Of course my suggested awk script can be turned into a single line of code. But, if you can't do that on your own, there is absolutely no possible way that the 1-liner version of that code will be easier to understand than the version I provided before. Code is always easier to understand if you can see the structure that shows, by indentation, how commands are connected. And, you can't include comments in the middle of an awk 1-liner, so I can't provide you with a commented 1-liner.

Hoping that comments will help you understand what the code is doing, I provide the following:
Code:
awk '	# Invoke awk and start the script specifying actions to be performed.
function print_total() {
	# Define function to print the total acccumulated for the previous set
	# of lines with the same four characters at the start of the 1st field.
	printf("\nTotal Sum of %s: %d\n", last, total)
}
last != substr($1, 1, 4) {
	# Perform the actions in this group when the 1st four characters in the
	# 1st field on this line is not the same as the 1st four characters in
	# the 1st field that we saw on the previous line.  Since there is no
	# previous line when we are reading the 1st line from our input file,
	# we also perform the actions in this group when processing the 1st
	# line in the input file.
	if(NR > 1) {
		# Perform these actions when we are not processing line #1.
		print_total()				# Print the total for
							# for the previous set.
		printf("\n=======================\n")	# Print a set separator.
	}
	# Save the 1st four characters from this line to compare against
	# subsequent input lines.
	last = substr($1, 1, 4)
	# Clear the total for this new set.
	total = 0
}
{	# Perform the actions in this group for every line in the input file.
	print		# Print the current input line.
	total += $2	# Add the contents of the 2nd field on this line to the
			# total for this set.
}
END {	# Perform the actions in this group after we have read the last line of
	# input from the input file.
	print_total()	# Print the total for the last set.
}' hhhh	# End the awk script and name the file to be processed.

This User Gave Thanks to Don Cragun For This Post:
# 5  
Old 08-15-2018
Don,
How can we get the average? based on the sum?

------ Post updated at 09:16 AM ------

Will get the total and average..
Code:
aaa1a 1
aaa1g 2
aaa1f 3

Total Sum of aaa1: 6

Total Average of aaa1: 2 #because 6/3

# 6  
Old 08-15-2018
Why don't you try adding processing for averages to the code I suggested.

If you can't get it to work, show us what you have tried and we'll help you fix it.
# 7  
Old 08-15-2018
Code:
awk '
function print_total() {
        printf("\nTotal Sum of %s site is: %d Mbps\n ", last, total)
}
function print_average() {
        printf("\nTotal Sum of %s site is: %d Mbps\n ", last, average)
}

last != substr($1, 1, 7) {
        if(NR > 1) {
                print_total()
                printf("\n=======================\n")
        }
        last = substr($1, 1, 7)
        total = 0
        average = 0
}
{       print
        total += $2
        average total/NR
}
END {   print_total()
        print_average()
}' hhhh > datarate.log
cat datarate.log

trying different combination but to no avail. Thank you
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

awk to average matching lines in file

The awk below executes and is close (producing the first 4 columns in desired). However, when I add the sum of $7, I get nothing returned. Basically, I am trying to combine all the matching $4 in f1 and output them with the average of $7 in each match. Thank you :). f1 ... (2 Replies)
Discussion started by: cmccabe
2 Replies

2. UNIX for Beginners Questions & Answers

Random letters

Hi there, first of all this is not homework...this is a new type of exercise for practicing vocabulary with my students. I have a file consisting of two columns, separated by a tab, each line consisting of a word and its definition, separated by a line break. What i need is to replace a... (15 Replies)
Discussion started by: eldeingles
15 Replies

3. Shell Programming and Scripting

Combine identical lines and average the one variable field

I have the following file 299899 chrX_299716_300082 196 78.2903 299991 chrX_299982_300000 18.2538 Tajd:0.745591 FayWu:-0.245701 T2:1.45 299899 chrX_299716_300082 196 78.2903 299991 chrX_299982_300000 18.2538 Tajd:0.745591 FayWu:-0.245701 T2:0.283 311027 chrX_310892_311162 300 91.6452... (2 Replies)
Discussion started by: jfern
2 Replies

4. Shell Programming and Scripting

Randomize letters

Hi, Is there a tool somewhat parallel to rev, but which randomizes instead of reverses? I've tried rl, but I can only get it to randomize words. I was hoping for something like this echo "hello" | ran leolh less simpler solutions are also welcome. Sorry if the question is... (21 Replies)
Discussion started by: jeppe83
21 Replies

5. Shell Programming and Scripting

How to add lines of a file and average them

I'm reading in numbers from a file and trying to add them together. Here is the code so far. I know the 1+2+3.... part is wrong. The file has five numbers in it with each number on its own line. The numbers are decimals if that matters. Thanks. while read EachLine do echo $EachLine done <... (6 Replies)
Discussion started by: AxlVanDamme
6 Replies

6. Shell Programming and Scripting

Perl- Finding average "frequency" of occurrence of duplicate lines

Hello, I am working with a perl script that tries to find the average "frequency" in which lines are duplicated. So far I've only managed to find the way to count how many times the lines are repeated, the code is as follows: perl -ae' my $filename= $ENV{'i'}; open (FILE, "$filename") or... (10 Replies)
Discussion started by: acsg
10 Replies

7. Shell Programming and Scripting

print running field average for a set of lines

Hi everyone, I have a program that generates logs that contains sections like this: IMAGE INPUT 81 0 0.995 2449470 0 1726 368 1 0.0635 0.3291 82 0 1.001 2448013 0 1666 365 1 0.0649 0.3235 83 0 1.009 2444822 0 1697 371 1 ... (3 Replies)
Discussion started by: euval
3 Replies

8. UNIX for Advanced & Expert Users

Add letters

I want to add letters A,B,C,… in front of every line of input while printing them out using PERL. eg A file is parsed as a cmd line arg and its context will be displayed as A line1... B line 2.. I tried this..but I want better and perfect solution! !perl -p my $counter; BEGIN { $counter... (4 Replies)
Discussion started by: aadi_uni
4 Replies

9. Shell Programming and Scripting

need to delete lines that start with letters

Hi, I need to remove all lines from a file that do not start with numbers For instance, if the first three characters on any line are not numbers, delete those lines I've tried to do it with awk and it's not working, any ideas ? Thanks (5 Replies)
Discussion started by: sfisk
5 Replies

10. Shell Programming and Scripting

transposing letters

Hi, I've written a shell function in bash that reads letters into an array, then outputs them in one column with: for n in "${array}"; do echo $n done I was wondering if anyone knew how i would transpose the letters that are output by the for loop. Right now my output is: aabbcc... (4 Replies)
Discussion started by: myscsa2004
4 Replies
Login or Register to Ask a Question