tags:

views:

100

answers:

7
+3  Q: 

Linux awk command

Hello,

I am a beginner in using Linux, I have an input file with content like:

00.11.11.11.11.11
177.22.22.22

one line of Ethernet address and one line of IP address, how can I convert this file to:

IP: 177.22.22.22  MAC: 00.11.11.11.11.11

I think awk would do it, but I don't know how. Any ideas?

Thanks!

+3  A: 
Jonathan Leffler
Yikes! @Jason, maybe you can put the IP and MAC on the same line with whitespace in between and `cat file | awk '{print "IP:", $1, "MAC:", $2}'` to achieve the same result.
greg
It works great, thank you so much!
Jason
Note that this skips blank lines or lines which don't match precisely 4 or 6 dotted decimal numbers - which may or may not be a virtue. The same MAC address could be used for a number of IP addresses, for example, if the data was not strictly alternating lines. Other solutions that do not scrutinize the input data are vulnerable to getting out of sync with the data - if the data is malformed.
Jonathan Leffler
+3  A: 

You can try it at ideone:

Really short!

{mac=$0;
 getline ip;
 print "IP: " ip  " MAC: " mac}
belisarius
very nice, thanks!
Jason
+3  A: 

paste - - < input_file | awk '{print "IP: " $2 " MAC: " $1}'

glenn jackman
Forgive my ignorance ... Does "paste - -" turn every two lines into one?
belisarius
paste turns its input into columns, the number of columns is the '- -'
Martin Beckett
nice! +1 // 7 more chars to go go
belisarius
+1  A: 
{ if(mac) { print "IP:", $0, "MAC:", mac; mac = 0 } else mac = $0 }
DigitalRoss
+2  A: 

awk -vRS= '{print "IP:", $2, "MAC:", $1;}'

which is equivalent to

awk 'BEGIN{RS="";}{print "IP:", $2, "MAC:", $1;}'

This works also with multiple input records:
"
00.11.22.33.44.55
123.45.67.89

11.22.33.44.55.66
11.22.33.99
"

->

"
IP: 123.45.67.89 MAC: 00.11.22.33.44.55
IP: 11.22.33.99 MAC: 11.22.33.44.55.66
"

kauppi
That requires blank lines separating the pairs of data lines.
glenn jackman
+1  A: 

Here's a sed version for variety:

sed 's/^/MAC: /;x;N;s/\n/IP: /;G;s/\n/  /' inputfile

If there is more than one pair of lines in the file:

sed 's/^/MAC: /;x;s/.*//;N;s/\n/IP: /;G;s/\n/  /' inputfile
Dennis Williamson
+1  A: 
awk -F"." 'NF>4{m=$0}NF==4{print "IP:"$0" MAC:"m}' file
ghostdog74