我有shell脚本,并且一段代码必须通过替换File1的column1值并填充File2的值来创建文件。
$ cat File1
CUST01,375
CUST02,379
和:
$ cat File2
CUST01,CUST01,233901
CUST01,CUST01,233902
File2所需的输出:
375,CUST01,233901
375,CUST01,233902
我尝试使用以下命令将值从File1填充到File2,
awk -F, 'NR==FNR { a[$1]=$2; next } { for(i in a) {for(x=1;x<=NF;x++) {$x=(i==$x)?a[i]:$x } } }1' File1 File2`
并低于输出
375,375,233901
375,375,233902
我只想替换column1中的对应值,而是awk方法导致替换所有列中的值,有帮助。
答案 0 :(得分:0)
您可以尝试执行此操作,但不进行错误检查:
declare -A dict
while IFS=, read -r key value; do
dict[$key]="$value"
done < file1
while IFS=, read -r col1 col2 col3; do
printf "%s,%s,%s\n" "${dict[$col1]}" "$col2" "$col3"
done < file2
说明
# create associativ array
declare -A dict
# read key and value from file, separator is ','
while IFS=, read -r key value; do
# write key and value into associativ array
dict[$key]="$value"
done < file1
# loop over file2, read three columns, separator is ','
while IFS=, read -r col1 col2 col3; do
# print columns, first column is the value from associativ array
printf "%s,%s,%s\n" "${dict[$col1]}" "$col2" "$col3"
done < file2
答案 1 :(得分:0)
当然不是awk
专家,但这似乎对我有用:
awk -v FS=',' -v OFS=',' 'NR == FNR { a[$1] = $2; next } { $1 = a[$2] }1' File1 File2
使用示例输入文件,这是输出:
375,CUST01,233901
375,CUST01,233902