AWK关联数组,映射 [英] AWK associative array, mapping
问题描述
假设我有两个文件:
文件1-map.txt
file1 - map.txt
1, 178246
2, 289789
3, 384275
4, 869282
file2-Relation.txt
file2 - relation.txt
178246, 289789
384275, 178246
384275, 869282
预期结果是:
1, 2
3, 1
3, 4
但是我使用以下代码得到的结果是:
But the results I got using the following code were:
awk 'FNR==NR{map[$2]=$1} {$1=map[$1];$2=map[$2];print $0}' map.txt relation.txt
2,
1,
4,
当我像这样交换map.txt中的列时,它很困惑:
It was confused when I swapped the columns in map.txt like this:
178246, 1
289789, 2
384275, 3
869282, 4
relation.txt不变
relation.txt doesn't change
结果变为:
awk 'FNR==NR{map[$1]=$2} {$1=map[$1];$2=map[$2];print $0}' map.txt relation.txt
1,
3,
3,
在{$ 1 = map [$ 1]; $ 2 = map [$ 2]; print $ 0}附近似乎出了什么问题
It seems that something wrong near {$1=map[$1];$2=map[$2];print $0}
推荐答案
删除第2列中两个文件中的前导空格.
Remove the leading space in both files in column 2.
帮自己一个忙,转到FS
的逗号以外的内容. Tab字符很不错,因为大多数输入屏幕都使用Tab移至下一个字段,因此它不应包含在您的数据中. |
char很不错,因为它很直观,而且不太可能出现在您的输入中.
And do yourself a favor and switch to something besides commas for FS
. The Tab char is good because most input screens use tab to move to the next field, so it shouldn't be in your data. The |
char is nice because it is visual and very unlikely to be in your input.
您可以构建一个陷阱"以查找没有正确数量的字段的记录,如下所示:
You could build a 'trap' to find records without the right number of fields like this:
awk -F"|" -v expectFldCnt=2 '{
if (NF==expectFldCnt) { print ":everything OK" ; }
else { print "ERR: " NF "!=" expectFldCnt ":" $0 > "errorFile" }
}' \
map.txt relation.txt
IHTH
这篇关于AWK关联数组,映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!