问题
I need to replace the value of the third column if the first two columns are same in two variables.
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
desired result:
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
回答1:
The right way:
awk -v OFS='\t' 'NR==FNR{ a[$1,$2]=$3; next }(($1,$2) in a){ $3=a[$1,$2] }1' <(echo "$s") <(echo "$b")
The output:
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
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
回答2:
Here is my solution:
awk 'NR==FNR{a[$1FS$2]=$3;next}$1FS$2 in a { $3 = a[$1FS$2] }1' <(echo "$s") <(echo "$b")
This one just takes $3 as the value stored in array a. Then if a match is found the substitution of $3 takes place.
来源:https://stackoverflow.com/questions/44757770/replace-the-value-of-third-column-if-the-first-two-columns-are-same-in-two-varia