Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep awk ignore character

Tags:

linux

grep

bash

awk

I'm trying to grep the value of "option dhcp-server-identifier" which is 192.168.75.1;

I'm not sure how to ignore the semicolon ";" at the end of IP address.

[root@localhost ~]# cat /var/lib/dhclient/dhclient-eth0.leases
lease {
interface "eth0";
fixed-address 192.168.75.54;
option subnet-mask 255.255.255.0;
option routers 192.168.75.1;
option dhcp-lease-time 4294967295;
option dhcp-message-type 5;
option domain-name-servers 192.168.75.1,8.8.8.8;
option dhcp-server-identifier 192.168.75.1;
option broadcast-address 192.168.75.255;
option host-name "centos-64-x86-64";
option domain-name "cs2cloud.internal";
renew 1 2081/12/15 18:43:55;
rebind 2 2132/12/30 03:09:24;
expire 6 2150/01/03 21:58:02;
}

I have tried the following

grep  dhcp-server-identifier /var/lib/dhclient/dhclient-eth0.leases | awk '{print $3}' 

result is 192.168.75.1;

Thanks

like image 985
Deano Avatar asked Dec 15 '22 03:12

Deano


2 Answers

Using awk

awk -F" |;" '/dhcp-server-identifier/ {print $3}' /var/lib/dhclient/dhclient-eth0.leases
192.168.75.1
like image 86
Jotne Avatar answered Jan 13 '23 12:01

Jotne


Remember that if you're grepping to awk, you can simply use awk. The following are equivalent:

$ grep  dhcp-server-identifier /var/lib/dhclient/dhclient-eth0.leases | awk '{print $3}'
$ awk  '/dhcp-server-identifier/ {print $3}' /var/lib/dhclients/dchclicent-eth0.leases

Your issue is that the semicolon appears on the end of the name. Instead of simply printing $3, we can use awk's substr function to remove that final character. Here's the reference to awk's manpage:

substr(s, m, n)
   the n-character substring of s that begins at position m counted from 1.

length the length of its argument taken as a string, or of $0 if no argument.

So, we need the substring of $3 from the first position (1), to the length of $3 minus that last character, so we need to go from the first character to length ($3) - 1:

substr($3, 1, length($3) - 1)

That should do it:

$ awk  '/dhcp-server-identifier/ {print substr($3, 1, length($3) - 1)}' /var/lib/dhclients/dchclicent-eth0.leases

That should do it.

like image 23
David W. Avatar answered Jan 13 '23 12:01

David W.