如果前两个列在两个变量中相同,则替换第三列的值 [英] Replace the value of third column if the first two columns are same in two variables

查看:90
本文介绍了如果前两个列在两个变量中相同,则替换第三列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个变量中的前两列相同,则需要替换第三列的值.

I need to replace the value of the third column if the first two columns are same in two variables.

我尝试过:使用NR===FNR存储第一个变量的第一列和第二列.然后,如果第一列和第二列相同 用变量"s"的第三列替换变量"b"的第三列.但是,执行$3=$3没有任何意义.

I tried: to store the first and second column of the first variable using NR===FNR. Then if first and second columns are same then replace the column three of variable "b" with third column of variable "s". However, doing $3=$3 does not make any sense.

awk 'NR==FNR{a[$1FS$2]=$1FS$2;next} $1FS$2 in a {$3=$3}1' <(echo "$s") <(echo "$b")
NODE AREA-29 1 UP ENABLED PINGABLE ASIA ACTIVE
NODE AREA-21 1 UP ENABLED PINGABLE ASIA ACTIVE
NODE AREA-20 1 UP ENABLED PINGABLE ASIA ACTIVE


echo "$b"
NODE  AREA-29  1   UP   ENABLED     PINGABLE  ASIA                   ACTIVE
NODE  AREA-21  1   UP   ENABLED     PINGABLE  ASIA                   ACTIVE
NODE  AREA-20  1   UP   ENABLED     PINGABLE  ASIA                   ACTIVE


echo "$s"
NODE  AREA-21   2
NODE  AREA-29   10
NODE  AREA-20   1

所需结果:

NODE  AREA-29  10  UP   ENABLED     PINGABLE  ASIA                   ACTIVE
NODE  AREA-21  2   UP   ENABLED     PINGABLE  ASIA                   ACTIVE
NODE  AREA-20  1   UP   ENABLED     PINGABLE  ASIA                   ACTIVE

推荐答案

正确的方法:

awk -v OFS='\t' 'NR==FNR{ a[$1,$2]=$3; next }(($1,$2) in a){ $3=a[$1,$2] }1' <(echo "$s") <(echo "$b")

输出:

NODE    AREA-29 10  UP  ENABLED PINGABLE    ASIA    ACTIVE
NODE    AREA-21 2   UP  ENABLED PINGABLE    ASIA    ACTIVE
NODE    AREA-20 1   UP  ENABLED PINGABLE    ASIA    ACTIVE


标准awk通过分隔下标来模拟多维数组 用逗号分隔的值.这些值被串联成一个字符串, 用 SUBSEP

Standard awk simulates multidimensional arrays by separating subscript values with commas. The values are concatenated into a single string, separated by the value of SUBSEP

这篇关于如果前两个列在两个变量中相同,则替换第三列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆