Home > Software design >  How to compare entries in one file to two files?
How to compare entries in one file to two files?

Time:02-04

I have a file (named file1) which consists of names and their IPs. It looks something like this :-

VM1 2.33.4.22
VM2 88.43.21.34
VM3 120.3.45.66
VM4 99.100.34.5
VM5 111.3.4.66

and i have two files (file2 and file3) which consists solely of IPs.

File 2 consists of:-

120.3.45.66
88.43.21.34

File 3 consists of :-

99.100.34.5

I want to compare file1 to file2 and file3 and get the names and IPs that are not present in file2 and file3. So output would be:

VM1 2.33.4.22
VM5 111.3.4.66

How can i get the desired output?

CodePudding user response:

sed 's/\./\\./g; s/.*/ &$/' file2 file3 | grep -vf - file1
  • Use sed to turn the entries in files 2 and 3 in to appropriate regexes.
  • Pipe this regex list to grep, with -f - to get the pattern list from standard input, and -v to print non matching lines in file 1.

CodePudding user response:

You can write a shell script that will do it for you.

#!/bin/sh
cat $1.txt $2.txt > mergedFile.txt
grep -v -f mergedFile.txt $3.txt

You can run the script by using the following command sh check.sh file2 file3 file1

CodePudding user response:

awk 'NR==FNR { out[$1]=1; next} !out[$2]' <(/bin/cat file2 file3) file1

This uses basically the same thing as the sed solution, using awk instead.

  •  Tags:  
  • Related