0

2 つのプロパティ ファイルがあり、ファイル A のキーと値のペアをファイル B の一致するキーと値のエントリに置き換えたいと考えています。ファイル A にはファイル B よりも多くのエントリがあります。まったく同じ数のエントリがあります。また、ファイル B には、ファイル A に含まれていないエントリが含まれている場合があります。

例として:

File A
"GB" = "United Kingdom";
"SE" = "Sweden";
"BR" = "Brazil";
"FR" = "France";
"ES" = "Spain";
"DE" = "Germany";

File B
"GB" = "Regno Unito";
"SE" = "Svezia";
"BR" = "Brasile";
"BR" = "Brasile";
"CL" = "Cile";

Desired Result
"GB" = "Regno Unito";
"SE" = "Svezia";
"BR" = "Brasile";
"FR" = "France";
"ES" = "Spain";
"DE" = "Germany";
"CL" = "Cile";

この検索と置換を bash を使用して実行することは可能ですか?

ありがとう、

ショーン

4

2 に答える 2

2

を使用する 1 つの方法を次に示しGNU awkます。

awk -F " = " 'FNR==NR { array[$1]=$2; next } $1 in array { sub ($2, array[$1]) }1' fileb filea

結果:

"GB" = "Regno Unito";
"SE" = "Svezia";
"BR" = "Brasile";
"FR" = "France";
"ES" = "Spain";
"DE" = "Germany";

編集:

置換が発生した後、配列要素を単純に削除できます。次に、スクリプトの最後に、残っているものを出力します。

awk -F " = " 'FNR==NR { array[$1]=$2; next } $1 in array { sub ($2, array[$1]); delete array[$1] }1; END { for (i in array) print i FS array[i] }' fileb filea

結果:

"GB" = "Regno Unito";
"SE" = "Svezia";
"BR" = "Brasile";
"FR" = "France";
"ES" = "Spain";
"DE" = "Germany";
"CL" = "Cile";
于 2012-11-01T00:34:51.173 に答える
1

次の bash 専用スクリプトは、求めている結果を吐き出します。

#!/bin/bash

# Identify our files. If you want, test for their existence before proceeding.
fileA="$1"
fileB="$2"

# Define an associated array
declare -A countries

# Read our initial data
while read cc junk name; do
 if [[ -n "$cc" ]]; then
   countries["$cc"]="$name"
 fi
done < "$fileA"

# Overwrite array elements with updated values
while read cc junk name; do
 if [[ -n "$cc" ]]; then
   countries["$cc"]="$name"
 fi
done < "$fileB"

# Print the results
for cc in "${!countries[@]}"; do
  echo "$cc = ${countries[$cc]}"
done

結果はまったく同じ順序にはなりませんが、それは重要ではないと思います。そうである場合は、インデックスがカウンターである追加の配列を作成し、 final の代わりに、for cc in ...その配列を単純にウォークスルーして$countries、正しい順序でインデックスを取得できます。それが重要であり、あなたがそれを理解できない場合はお知らせください。

あなたがbashソリューションを求めたので、私はこれをここに投稿するだけです. Steve のawkスクリプトははるかに簡潔で、おそらくはるかに高速です。(ただの推測です。おそらく、ベンチマークする時間すらもったいないでしょう。)

于 2012-11-01T03:39:26.367 に答える