【问题标题】:replace specific column values using reference of another file使用另一个文件的引用替换特定列值
【发布时间】:2019-05-23 10:29:36
【问题描述】:

我有 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 方法导致替换所有列中的值,任何帮助。

【问题讨论】:

  • 你的“所需输出”和你得到的输出在我看来是一样的。
  • 抱歉,这是由于自动更正造成的。我的预期输出是仅替换 column1 中的值。

标签: linux bash shell sh


【解决方案1】:

你可以试试这个,但它没有错误检查:

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

【讨论】:

  • 感谢 UtLox.. 它的工作原理,非常感谢您对每一行的解释。
【解决方案2】:

当然不是awk 专家,但这似乎对我有用:

awk -v FS=',' -v OFS=',' 'NR == FNR { a[$1] = $2; next } { $1 = a[$2] }1' File1 File2

使用您的示例输入文件,这是输出:

375,CUST01,233901
375,CUST01,233902

【讨论】:

  • 嗨,肖恩,谢谢.. 它适用于我上面的输入文件,但如果我的 File2 有 CUST02 并且输出应该显示来自 FIle1 (379) 的相应值,那是行不通的。
  • @SSK 它工作正常。将CUST02 添加到File2 并重新测试,它可以正常工作。您可能复制/粘贴错误。
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 2022-01-06
  • 2015-11-27
  • 1970-01-01
相关资源
最近更新 更多