我有两个文件,想要用 file2 中的值替换 file1 中的值。
文件1:
Normal A1
Normal A2
Normal A2,A3
Normal A4
文件2:
APP1 A1
APP2 A2
APP3 A3
APP4 A4
预期结果:
Normal APP1
Normal APP2
Normal APP2,APP3
Normal APP4
我尝试了以下命令,但没有得到预期的结果:
awk 'NR == FNR{a[$2]=$1; next}; -F "," {for (i=1; i<=NF; ++i) if ($i ~ ",") $i=a[$i]; else if ($i in a) $i=a[$i]; print}' File2 File1
答案1
可能之一awk
方法:
awk -F'[[:space:]]+|,' 'NR == FNR{ a[$2] = $1; next }
{
c = 0; r = $1 OFS;
for (i = 2; i <= NF; i++)
if ($i in a) { r = r (c++? "," : "") a[$i] }
if (!c) r = r $2;
print r
}' file2 file1
输出:
Normal APP1
Normal APP2
Normal APP2,APP3
Normal APP4