Home > OS >  Compare names and numbers in two files and output more
Compare names and numbers in two files and output more

Time:07-19

For example, there are 2 files:

$ cat file1.txt
e 16
a 9
c 14
b 9
f 25
g 7
$ cat file2.txt
a 10 
b 12
c 15
e 8
g 7

Сomparing these two files with the command(directory dir 1 contains file 1, in directory 2 respectively file 2) grep -xvFf "$dir2" "$dir1" | tee "$dir3" we get the following output in dir 3:

$ cat file3.txt
e 16
a 9
c 14
b 9
f 25

Now I need to essentially compare the output of file 3 and file 2 and output to file 3 only those results where the number next to the letter has become greater, if the number is equal to or less than the value in file 2, do not output these values to the 3rd file, that is the contents of file 3 should be like this:

$ cat file3.txt
e 16
f 25

CodePudding user response:

{m,g}awk 'FNR < NR ? __[$!_]< $NF : (__[$!_]= $NF)<_' f2.txt f1.txt
e 16
f 25

if u really wanna clump it all in one shot :

mawk '(__[$!!(_=NF)] = $_ * (NR==FNR)) <  $_' f2.txt f1.txt

CodePudding user response:

One awk idea:

awk '
FNR==NR { a[$1]=$2; next }      # 1st file: save line in array a[]
 ($1 in a) && ($2 > a[$1])      # 2nd file: print current line if 1st field is an index in array a[] *AND* 2nd field is greater than the corrsponding value from array a[]
!($1 in a)                      # 2nd file: print current line if 1st field is not an index in array a[]
' file2.txt file1.txt

This generates:

e 16
f 25
  • Related