restar una línea de un archivo a todas las líneas de otro archivo

restar una línea de un archivo a todas las líneas de otro archivo

Me gustaría restar columna por columna una línea de un archivo a todas las líneas de otro.

Aporte:file1

1 1 1 1
3 1 5 1
1 5 8 2

Aporte:file2

1 1 1 1

Salida deseada:file3

0 0 0 0
2 0 4 0
0 4 7 1

mal, sed?

Respuesta1

Con awk:

awk 'NR==1   { for(i=1; i<=NF; i++) a[i] = $i }
     FNR!=NR { for(i=1; i <NF; i++) $i -= a[i]; print }' file2 file1

Esto supone que:

  1. la línea relevante file2es siempre la primera
  2. la primera línea file2y todas las líneas file1tienen el mismo número de columnas
  3. Si hay varios espacios entre columnas, file1no le interesa conservarlos.

Respuesta2

tr ' -' ' _' < file1 |          # dashes -> underscores per dc requirements
dc -e "
[q]sq                           # macro for quitting
[z :x     z0<a]sa               # macro for main stack -> array x[]
[z ;x -SM z0<b]sb               # macro for doing: stack M = stack[i]-x[i]
[LMdn32an zlk>c]sc              # macro for printing stack M elements
[?z0=q lbx lcx 10Pc z0=?]s?     # do-while loop to read in file1 per line and run the macros "b" then "c"
$(< file2 tr ' -' ' _')         # load up the main stack with file2
zsk lax l?x                     # store cols in reg. k, call macro "a" and
" > file3

Resultados

0 0 0 0
2 0 4 0
0 4 7 1

Suposiciones

  1. ÑU CC
  2. Tantas columnas en el archivo 1 y el archivo 2, pero deberían ser iguales.

Respuesta3

Solución bash pura.

Uso: ./subtracting.sh file1 file2

#!/bin/bash

read -ra subtrahend < "$2"

while read -ra minuend; do
    for i in "${!minuend[@]}"; do
        echo -n $((minuend[$i] - subtrahend[$i]))
    done
    echo
done < "$1"

información relacionada