あるファイルの1行を別のファイルの全行から減算する

あるファイルの1行を別のファイルの全行から減算する

あるファイルの 1 行を、別のファイルのすべての行から列ごとに減算したいと思います。

入力:file1

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

入力:file2

1 1 1 1

望ましい出力:file3

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

awk、sed?

答え1

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

これは次のことを前提としています:

  1. 関連する行はfile2常に最初の行です
  2. の最初の行file2と のすべての行file1の列数は同じです
  3. 列間に複数のスペースがある場合、file1それらを保持する必要はありません。

答え2

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

結果

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

仮定

  1. GNU dc
  2. file1 と file2 には同じ数の列がありますが、それらは同じである必要があります。

答え3

純粋な bash ソリューション。

使用法: ./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"

関連情報