I am trying to parse dhcp.lease file from /tmp/dhcp.lease in openwrt .
root@OpenWrt:/# cat /tmp/dhcp.leases
1568953482 70:B3:D5:14:D0:31 192.168.3.51 device1 01:70:B3:D5:14:D0:31
2867821468 38:B8:EB:10:00:22 192.168.5.93 device2 01:38:B8:EB:10:00:22
8984532872 00:01:0A:33:11:33 192.168.5.44 CISCOee 01:00:01:0A:33:11:33
Where, 2nd column - MAC address , 3rd column - IP address and 4th column- Name
I want to run a shell script to parse No of devices
, MAC address
, IP address
and Device Name
from this dhcp.lease list .
sample output :
if there is 3 device
list is present in dhpcp.lease
file , I want to print output like :
3
70:B3:D5:14:D0:31/192.168.3.51/device1
38:B8:EB:10:00:22/192.168.5.93/device2
00:01:0A:33:11:33/192.168.5.44/CISCOee
and if no device list found , it should return
0
Can i do with simple file content iteration ? or any fast method like sed/awk ? Any sample code ?
awk
command may help you.
$ awk -v OFS='\n' '$2 ~ /[0-9A-Z]:/{n=n+1;a[n]=$2"/"$3"/"$4} END{print n==""?0:n; for(i in a)print a[i]}' /tmp/dhcp.leases
Brief explanation,
$2
matched to regex [0-9A-Z]:
n
, and also save $2/$3/$3
to the array a
n
and the value in the array a
in the end The previous awk statement seems over complicated to me. The following is simpler:
awk '{ dat[NR]=$2"/"$3"/"$4 } END { print NR;for ( i=1;i<=NR;i++) { print dat[i] } }' /tmp/dhcp.lease
The leases file is in a fixed format with just the data required and the total count will be the number of records (NR variable). Read the data required into an array dat and then print NR and loop through the array printing each entry.
Besides awk
, you can use grep
with regex
and using a temporary file in where you'll save the matched output for further counting its lines and displaying it like this example:
~$ cat /tmp/dhcp.leases | grep -oE "([0-9A-Z]{2}:){5}[0-9A-Z]{2}.*([0-9]{1,3}\.){3}[0-9]{1,3}.*[a-zA-Z]{3,}[0-9]+?" | tr ' ' '/' > /tmp/testFile
~$ cat /tmp/testFile | wc -l; cat /tmp/testFile
Output:
3
70:B3:D5:14:D0:31/192.168.3.51/device1
38:B8:EB:10:00:22/192.168.5.93/device2
00:01:0A:33:11:33/192.168.5.44/CISCOee
Explanation:
o
nly the matched (non-empty) parts of the matching line and use the E
xtended regexp see the man page . /tmp/testFile
. /tmp/testFile
using wc
and print its lines.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.