シェルを使用して両方のファイルの値を計算し、結果を別のファイルに保存する必要があります。

シェルを使用して両方のファイルの値を計算し、結果を別のファイルに保存する必要があります。

両方のファイルの値を計算し、結果を出力ファイルに保存する必要があります。出力ファイルでは、各レコードは入力ファイル内の同じ名前のレコードの結果を表示します。

文書1

s1 10
s2 20 
s3 25 
s4 25  
s5 25   
s6 20 
s7 25 
s8 25

文書2

s2 4
s1 10
s3 2 
s4 3 
s6 3
s7 2
s8 2 

出力

s1 100 
s2 80 
s3 50
s4 75 
s6 60 
s7 50 
s8 50

注:シェルを使用する必要があります。

ベストアンサー1

このスクリプトは必要なタスクを実行します。ファイルが常に次の形式であるとします。

id value, id2 value2, id3 value3

つまり、カンマ区切りフィールドと2つのファイルの間の一貫した形式を想定しています。また、最新バージョンがbashインデックス配列をサポートしていると仮定します。また、正しい出力、つまり表示された出力(例:2x25!= 75)ではなく、要求された出力も提供します。

#!/usr/bin/env bash

## Read each line of the first file into the 
## array lines1.
mapfile -t lines1 < file1
## Do the same for the 2nd file and the array lines2.
mapfile -t lines2 < file2


declare -A fields2
declare -A fields1
## Iterate through each element of $lines2
## and separate ids from values
for ((i=0; i<${#lines2[@]}; i++)); do
    while read id val
    do
        fields2["$id"]="$val"
    done < <(printf "%s\n" "${lines2[$i]//, /$'\n'}")
done

## Iterate through each element of $lines1, separate
## ids from values.
for ((i=0; i<${#lines1[@]}; i++)); do
    while read id val
    do
        ## Some ids don't exist in both files, set their 
        ## value to 1 to avoid errors.
        if [[ -z "${fields2[$id]}" ]]; then
            fields2[$id]=1
        fi
        ## Print the id and the result of the multiplication.
        printf "%s %d " $id  "$(( ${fields2[$id]} * $val ))";
    done < <(printf "%s\n" "${lines1[$i]//, /$'\n'}")
    echo "";
done

おすすめ記事