1

Input:

192.168.0.1 aa:bb:cc:00:11:22 192.168.0.1 aa:00:bb:11:cc:22
192.168.10.11 2a:bb:cc:20:11:22 192.168.10.11 aa:02:bb:21:cc:22

Output:

3232235521 187723558162722 3232235521 186920115227682
3232238091 46986071904546 3232238091 186928706210850

I know how to convert mac to int (hex -> int) in python3 : mac = int(mac.replace(':', ''), 16) But I cant' apply this method in shell. Also don't know about IP to Int.

I want to using awk, like this:

awk '{$1,$3=??, $2,$4=???}' tmpfile > newfile
matiii
  • 55
  • 5

3 Answers3

2

With GNU awk for strtonum():

$ echo 'aa:bb:cc:00:11:22' | awk '{gsub(/:/,""); print strtonum("0x"$0)}'
187723558162722

$ echo '192.168.0.1' | awk '{split($0,o,/[.]/); print o[1]*256^3 + o[2]*256^2 + o[3]*256 + o[4]}'
3232235521

$ cat tst.awk
function ip2int(ip,  o) { split(ip,o,/[.]/); return o[1]*256^3 + o[2]*256^2 + o[3]*256 + o[4] }
function mac2int(mac)   { gsub(/:/,"",mac); return strtonum("0x"mac) }
{ print ip2int($1), mac2int($2), ip2int($3), mac2int($4) }

$ awk -f tst.awk file
3232235521 187723558162722 3232235521 186920115227682
3232238091 46986071904546 3232238091 186928706210850
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • Can I use this method like in this pattern? : `awk '{$2=gsub(/:/,""); print strtonum("0x"$0)}' tmp` But its outputs are '0 ...' – matiii Aug 20 '21 at 23:19
  • @matiii `gsub()` returns how many replacements it made, not the modified string. I added the full code to get the output you want from the input you posted. – Ed Morton Aug 20 '21 at 23:21
  • 1
    Now I see. I didn't figure out about your script(tst.awk). Now I found out! Thanks a lot. – matiii Aug 20 '21 at 23:25
0

Try this Perl one-liner

$ cat matii.txt
192.168.0.1 aa:bb:cc:00:11:22 192.168.0.1 aa:00:bb:11:cc:22
192.168.10.11 2a:bb:cc:20:11:22 192.168.10.11 aa:02:bb:21:cc:22

perl -pe ' s/(\d+)\.(\d+)\.(\d+).(\d+)/$1*256**3+$2*256**2+$3*256+$4/ge; s/://g ; s/\S+\s+\K(\S+)/hex($1)/ge;' matii.txt
3232235521 187723558162722 3232235521 186920115227682
3232238091 46986071904546 3232238091 186928706210850
stack0114106
  • 8,534
  • 3
  • 13
  • 38
-1

The Perl equivalent of

mac = int(mac.replace(':', ''), 16)

is

$mac = hex( $max =~ s/://rg )

A solution:

perl -nle'print join " ", unpack "N Q> N Q>", pack "( C4 xx(H2)6 )2", /[0-9a-fA-F]+/g'

Specifying file to process to Perl one-liner


A clearer solution:

perl -lane'
   sub ipv4_to_dec { unpack "N", pack "C4", split /\./, $_[0] }
   sub mac_to_dec { hex( $_[0] =~ s/://rg ) }
   print join " ",
      ipv4_to_dec($F[0]), mac_to_dec($F[1]),
      ipv4_to_dec($F[2]), mac_to_dec($F[3]);
'

or

perl -ple'
   sub ipv4_to_dec { unpack "N", pack "C4", split /\./, $_[0] }
   sub mac_to_dec { hex( $_[0] =~ s/://rg ) }
   s{\G(\s*)(\S+)(\s+)(\S+)}{ $1 . ipv4_to_dec($2) . $3 . mac_to_dec($4) }eg;
'
ikegami
  • 367,544
  • 15
  • 269
  • 518