Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a long .csv file that consists of device information. Each line is a unique device with its own info listed as such: MACaddr,,,,Date,Date,,"b,n",,blahblahblah. It's irrelevant what that all stands for.

What I need to do is take in the file and then write to a new file with all lines/devices that have the same Vendor MAC (i.e. the first 3 octets of the MAC Address) grouped together. I can easily take in each line and grab the Vendor MAC with a regex but then I am stuck.

All I have is:

#!usr/bin/perl
use strict;
use warnings;

open IN, "wirelessClients.csv" or die "Couldn't open file\n$!";
open OUT, ">sortedClients.csv" or die "Couldn't open out file\n$!";

my @clients = <IN>;

foreach my $client (@clients)
{
    if($client =~ /^(\w+:\w+:\w+)/)
    {
        print OUT "$1,$client\n\n"; 
    }
}

I have no idea how to go about sorting the information.

Any help and/or guidance would be greatly appreciated!

share|improve this question
Consider using lexical filehandles unless you've a deep reason not to. – pilcrow 38 mins ago
Oh wow, well that was incredibly simple... I was thinking wayyyyyy to hard. Thank you! – user215654 34 mins ago
And good information, pilcrow, thank you. I will adjust my ways. – user215654 31 mins ago
You're welcome. Moved to an answer so you can close off the question. – RobEarl 30 mins ago
@pilcrow On an 8-line script?! Whyever for? That’s like saying never have mainline code, but only write modules with subroutines. There are plenty of more important things to worry about.\n\n\n\n – tchrist 16 mins ago
add comment (requires an account with 50 reputation)

2 Answers

up vote 2 down vote accepted

If the MAC address is the first element, a simple sort should group ones with the same first 3 octets:

sort wirelessClients.csv > sortedClients.csv
share|improve this answer
Useless use of cat. –1 – tchrist 17 mins ago
Thanks @tchrist, I should know better! – RobEarl 14 mins ago
add comment (requires an account with 50 reputation)

As we're looking at the first octets anyway you can simply sort numerically:

#!/usr/bin/perl

use strict;
use warnings;


open (my $in, '<', "wirelessClients.csv") or die "$!";
open (my $out, '>',"sortedClients.csv") or die "$!";

my @clients = <$in>;

my @sorted = sort {$a <=> $b} @clients;

foreach @sorted {
    print $out, $_;
}
share|improve this answer
How is the programmer to know which file caused the error? – tchrist 11 mins ago
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.