Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

comparing 2 arrays for invalid mac addresses only 3

Status
Not open for further replies.

rigstars2

Instructor
Dec 18, 2011
64
US
I have 2 arrays and I want to compare and only print the non-valid macs in red/bold. The valid macs array will always be constant. I tried comparing 1 element at a time but doesn't work as it would still pick up valid array elements. Any help would be appreciated.

valid macs
90:40:95:29:C4:81
88:E9:10:20:49:8B
F0:F6:1C:9E:50:70

Log file with valid and invalid macs
[highlight #EF2929]1B:BB:1C:7D:34:77[/highlight]
88:E9:10:20:49:8B
F0:F6:1C:9E:50:70
[highlight #EF2929]F8:8A:2C:5F:FD:49[/highlight]
90:40:95:29:C4:81
 
A perl 1-liner ;)
Code:
$ perl -e '%valid=(); open FH,$ARGV[0];while(<FH>){chomp;$valid{$_}=1;};close FH;open FH,$ARGV[1];while(<FH>){chomp;print "$_\n" if ( !defined $valid{$_} );};close FH;' 1st_file.txt 2nd_file.txt 
1B:BB:1C:7D:34:77
F8:8A:2C:5F:FD:49

Or formatted for readability
Code:
$ perl -e '%valid=();
  open FH,$ARGV[0];
  while(<FH>){
    chomp;
    $valid{$_}=1;
  };
  close FH;
  open FH,$ARGV[1];
  while(<FH>){
    chomp;
    print "$_\n" if ( !defined $valid{$_} );
  };
  close FH;' 1st_file.txt 2nd_file.txt 
1B:BB:1C:7D:34:77
F8:8A:2C:5F:FD:49

1st_file.txt is the valid list.
2nd_file.txt is the mixed list.

--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Salem,

Wow, I appreciate this but I'm introducing folks bash scripts not perl. We'd like to be at level at some point. Can you provide a bash script version instead please? Thanks in advance.
 
I think this will do ..thanks for the help Salem!

var=$(comm -1 -3 <(sort ~/valid.txt) <(sort ~/invalid.txt))
for ((i = 0; i < ${#var[@]}; i++)); do
echo "${var}" > ~/invalid_macs.txt
done
 
Hi

My first thought on such task is usually [tt]grep[/tt] :
Code:
grep -xvf valid-macs valid-and-invalid-macs > invalid-macs

But I like your [tt]comm[/tt] solution too. Somehow we never got close to each other and never noticed its [tt]-1[/tt] / [tt]-2[/tt] / [tt]-3[/tt] switches.


Feherke.
feherke.github.io
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top