У меня много файлов, названных так: DOS1, DOS2, DOS3, DOS4, ..., DOS128. Каждый файл содержит четыре столбца (первый столбец один и тот же) с цифрами, например:
DOS1:
33 12 1 2
16 32 8 1
9 90 17 5
...
DOS2:
33 1 2 1
16 3 4 3
9 1 1 1
...
Я хотел бы суммировать второй, третий и четыре столбца из указанных файлов DOSX, например DOS1 и DOS2, для получения DOS_sum:
33 13 3 3
16 35 12 4
9 91 18 6
...
Как это сделать?
С 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
Более читаемо:
{
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]
}
Используйте расширение раскладки bash для суммирования последовательности файлов:
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}
С 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
Более читаемо:
{
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]
}
Используйте расширение раскладки bash для суммирования последовательности файлов:
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}
С 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
Более читаемо:
{
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]
}
Используйте расширение раскладки bash для суммирования последовательности файлов:
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}