我需要将文件 1 的第 4 列(等级)与文件 2 的第 1 列(等级)相匹配。如果匹配,则将 File1 的第 4 列(等级)替换为 File2 的第 2 列(标记)。如果不匹配,则保留第 4 列(等级)的值不变。
文件1
"RollNo","Name","Age","Grade","Class","Teacher"
"1","Asha","7","A","1","David"
"2","Mona","7","B","1","David"
"3","Sonali","7","C","1","David"
"4","Rani","7","D","1","David"
"5","Raj","7","B","1","David"
文件2
"Grade","Marks"
"A","90"
"B","80"
"C","70"
预期输出:
"RollNo","Name","Age","Grade","Class","Teacher"
"1","Asha","7","90","1","David"
"2","Mona","7","80","1","David"
"3","Sonali","7","70","1","David"
"4","Rani","7","D","1","David"
"5","Raj","7","80","1","David"
您能帮我使用 awk 命令来输出此输出吗?
期待您的回复。
答案1
假设 CSV 中的字段不能包含,
s 或换行符 ( \n
) 并且您正在运行 Unix shell:
$ awk '
BEGIN { FS=OFS="," }
NR==FNR { map[$1] = $2; next }
(FNR>1) && ($4 in map) { $4 = map[$4] }
1' file2 file1
"RollNo","Name","Age","Grade","Class","Teacher"
"1","Asha","7","90","1","David"
"2","Mona","7","80","1","David"
"3","Sonali","7","70","1","David"
"4","Rani","7","D","1","David"
"5","Raj","7","80","1","David"