Linux Shell Text Processing – How to Sum Up Values of Each Two Rows Across Their Line in Linux

awklinuxperlshelltext processing

I have a data like this:

input.txt

1 0000100101000000
1 0000010100000000
2 1110000001000000
2 1111000000001000
3 0000000111111111
3 1111111100000000
4 8888345500000000
4 0000000000000000

and I want to sum up the values within eachtwo rows with the same row number:
output:

output.txt

1 0000110201000000
2 2221000001001000
3 1111111211111111
4 8888345500000000

any suggestion please? my real dat had 8000 rows with 45000 digit in each line

Best Answer

sed '
    N                                                       #append next line
    s/$/))/                                                 #add `))` to end
    s/\(\S*\s*\)\(.*\)\n\1/printf "%016d\n" \$((10#\2+10#/  #check Nos, form line
    t                                                       #to end if Nos equal
    s/))$//                                                 #remove `))`
    D                                                       #delete 1st line
    ' file |
bash

Regarding 45000 digits number please note that maximum number which bash can handle is

/* Minimum and maximum values a `signed long int' can hold.  */
#  if __WORDSIZE == 64
#   define LONG_MAX 9223372036854775807L
#  else
#   define LONG_MAX 2147483647L
#  endif

[ 1 ] /usr/include/limits.h

Related Question