ファイルで見つかったすべての文字列を他のファイルの値に置き換える

ファイルで見つかったすべての文字列を他のファイルの値に置き換える

data.csv次のCSVファイル()があります。

apple_val, balloon_val, cherry_val, dog_val
1         ,5           ,6          ,7
3         ,19          ,2          ,3

sentence.txt次のテキストファイル()があります。

I have apple_val apple(s) and balloon_val balloons. My dog_val dogs were biting the cherry_val cherries. 

output.txt私の出力ファイル()を次のように作成したいと思います。

I have 1 apple(s) and 5 balloons. My 7 dogs were biting the 6 cherries.
I have 3 apple(s) and 19 balloons. My 3 dogs were biting the 2 cherries. 

以下のスクリプトを使用しました。しかし、私のスクリプトは上記の例にのみ適用されます。

awk -F "," {print $1, $2, $3, $4} data.csv | while read a, b, c,d
do
    sed -e "s/apple_val/$a/g" -e "s/balloon_val/$b/g" -e "s/dog_val/$d/g" -e "s/cherry_val/$c/g" sentence.txt >> output.txt
done

CSVファイルの最初の行(ヘッダ)を読み、テキストファイル内のこれらの文字列(apple_valなど)を置き換えて通常のファイルにしたいと思います。

どうすればいいですか?

ベストアンサー1

修正済みエイリアン変形(配列を使用):

#!/bin/bash
tr -s ',' ' ' <data.csv | {
read -a tokens
while read -a values; do
    for index in $(seq 0 $((${#tokens[*]}-1))); do
        echo "s/${tokens[$index]}/${values[$index]}/g"
    done | sed -f - sentence.txt
done
}

awk同じ

awk -F"[, ]+" '
NR == FNR{
    s=s $0 "\n"
    next}
FNR == 1{
    for(i=1;i<=NF;i++)
        val[i]=$i
    next}
{
    p=s
    for(i=1;i<=NF;i++)
        gsub(val[i], $i, p)
    printf p}
' sentence.txt data.csv

おすすめ記事