Shell 使用awk在word中从一个文件查找到另一个文件,NR==FNR
我正在尝试使用以下awk命令从一个文件到另一个文件查找单词:Shell 使用awk在word中从一个文件查找到另一个文件,NR==FNR,shell,awk,Shell,Awk,我正在尝试使用以下awk命令从一个文件到另一个文件查找单词: awk 'NR==FNR{a[$2]=$1;next}($1 in a){print a[$2] " " $2}' file1 file2 档案内容包括: 文件1: 维杜1 黑帮2 文件2: 11 24980022 预期产出: 维杜1 gangwar 4980022 但产出是这样的: 维杜1 4980022 帮我找出这个问题 试试看: awk 'FNR==NR{A[$2]=$1;next} ($1 in A){print A[$1
awk 'NR==FNR{a[$2]=$1;next}($1 in a){print a[$2] " " $2}' file1 file2
档案内容包括:
文件1:
维杜1
黑帮2
文件2:
11
24980022
预期产出:
维杜1
gangwar 4980022
但产出是这样的:
维杜1
4980022
帮我找出这个问题 试试看:
awk 'FNR==NR{A[$2]=$1;next} ($1 in A){print A[$1], $2}' Input_file1 Input_file2
说明:
awk 'FNR==NR #### Checking condition of FNR==NR which will be TRUE when first Input_file1 is being read.
{A[$2]=$1; #### create an array named A with index of field 2 and have value as first field.
next} #### using next keyword(built-in awk) so it will skip all next statements.
($1 in A) #### Now checking if first field of file2 is present in array A, this will be checked only when Input_file2 is being read.
{print A[$1], $2 #### printing value of array A's value whose index is $1 and $2 of Input_file2.
}' Input_file1 Input_file2 #### Mentioning the Input_file1 and Input_file2 here.
您也可以使用类似以下内容:
join -1 2 -2 1 file1 file2 -o 1.1,2.2
假设您的文件是按顺序排序的
如果没有,则首先对它们进行排序。使用
(a中的$1){print a[$2]
您正在测试$1
是否作为索引存在于a[]
中,但随后尝试打印a[]
被一个完全不同的值索引,$2
。想想看…@EdMorton非常感谢您指出了这个逻辑错误。+1但是为了清晰起见并避免与内置变量冲突,不要在awk或shell中使用所有大写变量名(shell中导出的变量除外).谢谢你Ed Morton的鼓励:)