简体   繁体   中英

compare two files using awk

PFB the scenario

I have two files

file 1

val1
val2
val3 

file 2

val1
val2
val4

the below code would give me all matching rows

awk 'FNR==NR{arr[$1];next}$1 in arr{print $1,"in both files"} file1 file2

the output would be

 val1 in both files
 val2 in both files

But what I wanted is

val4

how can I change the code so that I can get the value which are NOT PRESENT in the array arr.

Use ! operator to print the values in file2 but not in file1.

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

I tried it and output is :

$ cat file1              
val2
val3
$ cat file2               
val1
val2
val4
$ awk 'FNR==NR{a[$1]++;next} !($1 in a)' file1 file2
val4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM