將一個文件中的一行減去另一個文件中的所有行

將一個文件中的一行減去另一個文件中的所有行

我想將一個文件中的一行逐列減去另一個文件中的所有行。

輸入: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直流電
  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"

相關內容