使用awk比较两个不同文件中的两列

我有以下两个文件

file1

1|a
2|b
3|c
4|d
5|e
6|g
7|h
8|i

file2

2
3

在Linux中使用awk的预期输出

1|a
4|d
5|e
6|g
7|h
8|i

在下面尝试过但未达到预期的操作

awk '{k=$1 FS $2} NR!=FNR{a[k]; next} !(k in a)' file1 file2

在Linux中使用awk的预期输出

1|a
4|d
5|e
6|g
7|h
8|i
qq329119652 回答:使用awk比较两个不同文件中的两列

我们必须为两个Input_file设置不同的FS,因为一旦Input_file用PIPE(|)分隔了,而其他则没有,请您试一下。这只会打印那些不在Input_file2中但存在于Input_file1中的行。

awk 'FNR==NR{a[$0];next} !($1 in a)'  Input_file2  FS="|"  Input_file1

输出如下。

1|a
4|d
5|e
6|g
7|h
8|i


说明: 添加上述命令的说明。

awk '                                       ##Starting awk program from here.
FNR==NR{                                    ##Checking condition FNR==NR which will be TRUE when Input_file2 is being read.
  a[$0]                                     ##Creating an array named a whose index is $0 here.
  next                                      ##next function is awk out of the box function which skips all further statements from here onward.
}                                           ##Closing BLOCK for FNR==NR condition here.
!($1 in a)                                  ##Checking condition if $1 is NOT present in Input_file1,this condition will be executed when Input_file named Input_file1 is being read.
'  Input_file2  FS="|"  Input_file1         ##Mentioning Input_file2 name then setting FS as pipe and mentioning Input_file1 here.
本文链接:https://www.f2er.com/3158754.html

大家都在问