2

I have a lot of files named like this: DOS1, DOS2, DOS3, DOS4, ..., DOS128. Each file contains four columns (first column is the same) with numbers, like this:

DOS1 is:

33 12 1 2
16 32 8 1
9  90 17 5
...

DOS2 is:

33 1 2 1
16 3 4 3
9  1 1 1
...

I would like to sum the second, third and four column from specified DOSX files, for example DOS1 and DOS2, to get DOS_sum:

33 13 3 3
16 35 12 4
9  91 18 6
...

How can I do this?

4

With awk:

awk '{a[FNR]=$1;b[FNR]+=$2;c[FNR]+=$3;d[FNR]+=$4} END{for (i=1;i<=FNR;i++) print a[i], b[i], b[i], d[i]}' DOS1 DOS2 > DOS_sum

More readably:

{
    a[FNR]=$1     # Keep the first column
    b[FNR]+=$2    # Sum the rest. FNR is the current line number 
    c[FNR]+=$3    # in the current file. So this accumulates
    d[FNR]+=$4    # the values of a given line number across files.
}
END {
    for (i=1; i<=FNR; i++) 
        print a[i], b[i], c[i], d[i]
}

Use bash's brace expansion to sum a sequence of files:

awk '{a[FNR]=$1;b[FNR]+=$2;c[FNR]+=$3;d[FNR]+=$4} END{for (i=1;i<=FNR;i++) print a[i], b[i], b[i], d[i]}' DOS{10..73}
  • Dear muru, thank you for prompt response. There is a small typo: a{FNR]=$1 -> a[FNR]=$1.After correction it works perfect, do you have an idea how to sum up more specified files without giving their name by hand? For example, sum up columns (with method you gave) of files let say from DOS10 to DOS73. – Piotr Oct 8 '17 at 10:57
  • @Piotr ah, sorry about that. – muru Oct 8 '17 at 10:58
  • For a sequence of files, use brace expansion. See update – muru Oct 8 '17 at 11:09
  • Thank You again, it seems that everything works fine. Great job :D – Piotr Oct 8 '17 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.