2

I have a file with MAC addresses (1/line with : as separator, sorted) and I need to find out how many times each of these MAC addresses appears in the file. I modified this:

How to count occurrences of all the words in all the files of a directory using grep? But with count incremented only once per word per file

... a bit to get this:

#!/bin/sh

grep -o -h -E '\w+' macadd | sort -u | \
while read word;
do
        # iterate through each word and find how many files it occurs
        c=`grep "$word" macadd | wc -l`
        echo "$c    $word";
done

Which produces this output:

$ ./test.sh
12    00
84    08
6    09
36    0A
84    0B
1415    0C
4    10
6    12
68    13

... which is obviously isn't what I'm looking for. When I remove : from the source file, I get this:

6    00EEBDA24AE1
3    10AE605A727A
6    2847AAC81C88
2    34C059B368DC
10    4C3C1655CD6A
1415    4C7F62310CD0
1    50CCF8BA10D7

... which gives me what I want, but I'd like to retain the : separator for various reasons. It'd be also nice to have the width of the first column standard to produce a table output:

6    00:EE:BD:A2:4A:E1
3    10:AE:60:5A:72:7A
6    28:47:AA:C8:1C:88
2    34:C0:59:B3:68:DC
10   4C:3C:16:55:CD:6A
1415 4C:7F:62:31:0C:D0
1    50:CC:F8:BA:10:D7

Where to go from here?

Thanks in advance.

  • 1
    It sounds like you are reinventing uniq -c – steeldriver Mar 30 '15 at 23:42
  • AAARRRGGGHHH!!! :D I was indeed, thanks :) If you'd be kind to make that an answer... – Peregrino69 Mar 30 '15 at 23:44
1

Try this

sort macadd | uniq -c
2

All you need is sort macadd | uniq -c as explained by @roaima but I just wanted to point out how you could do it using the same approach you had attempted.

There's no reason to grep through the file, you can just feed it directly to while:

while read mac; do echo "$mac"; done < macadd

Also, grep has a -c option which counts matches. So, with a couple of small tweaks, you can do what you were attempting using the tools you were using:

$ while read mac; do 
    printf "%5s\t%s\n" $(grep -c "$mac" macadd) "$mac"; 
  done < <(sort -u macadd)
   6     00:EE:BD:A2:4A:E1
   3     10:AE:60:5A:72:7A
   6     28:47:AA:C8:1C:88
   2     34:C0:59:B3:68:DC
  10     4C:3C:16:55:CD:6A
1415     4C:7F:62:31:0C:D0
   1     50:CC:F8:BA:10:D7

Now, your grep was failing because : is not considered a word-character, so is not matched by \w. You could instead have used something like this:

grep -ohE '[A-Z0-9:]+' macadd | sort -u 

But there's no need for grep since sort can do it by itself (always assuming that your file has nothing but MAC addresses):

sort -u macadd | while read . . .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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