Summing over specific lines and replacing the lines with the sum

Hi friends,

This is sed & awk type question. It is slightly different from my previous question.

I have a text file which has numbers spread all over the file. I want to sum the series of numbers (but no more than 10 numbers in series) whenever i find it and produce an output file with the sum. For example

###start of input text file ####

abc
def
ghi
1
2
3
4
5
6
7
8
9
10
11
12
13
kjld
random
text
occupies
some
1000
3000
400
again
some
random
text
900
100
whatever
is here
900
11
what

#####end of input file #########

The output should be

##start of output file ####

abc
def
ghi
55
36
kjld
random
text
occupies
some
4400
again
some
random
text
1000
whatever
is here
911
what

########### end of output file #################

So the output file is the same as the input file, except the series of numbers (where series consists of ten or less consecutive numbers) is replace by its sum.

I hope it makes sense. If not, please let me know any questions.

Kind Regards,

Let me know ,what desired output you want?

1 Like

bmk dude

The desired output is shown right below the input data

Here you go again

abc
def
ghi
55
36
kjld
random
text
occupies
some
4400
again
some
random
text
1000
whatever
is here
911
what

try this...

 
 
$ awk '{if($0~/^[0-9]*$/){a+=$0;c++}if(c>=10){print a;a=c=0}if($0!~/^[0-9]*$/){if(a!=0 && c<10){print a"\n"$0;a=0}else{print}}}' input.txt
abc
def
ghi
55
36
kjld
random
text
occupies
some
4400
again
some
random
text
1000
whatever
is here
911
what

1 Like

itkamaraj.

Thanks a lot due.

Really appreciate