开发者

Linux awk command

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
开发者_JAVA百科

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!


It could be done with 'sed', too, but since you ask for 'awk', 'awk' it shall be.

awk '/^([0-9]+\.){5}[0-9]+$/ { mac = $1 }
     /^([0-9]+\.){3}[0-9]+$/ { printf "IP: %s MAC: %s\n", $1, mac }' data

(Previous version:

awk '/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ { mac = $1 }
     /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ { printf "IP: %s MAC: %s\n", $1, mac }'

Not so good because of the written out repeat, instead of counted repeat.)

The first line matches MAC addresses and saves the most recent in variable mac. The second matches IP (IPv4) addresses and prints the current MAC address and IP address.

If you have stray leading or trailing blanks, or other stray characters, you need to make the regexes appropriately more complicated.


You can try it at ideone:

Really short!

{mac=$0;
 getline ip;
 print "IP: " ip  " MAC: " mac}


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


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
"


{ if(mac) { print "IP:", $0, "MAC:", mac; mac = 0 } else mac = $0 }


awk -F"." 'NF>4{m=$0}NF==4{print "IP:"$0" MAC:"m}' file


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜