Regular expression using grep to extract an IP address - regex

I am trying to parse the default IP address of the default route.
I already have the default route and I'm trying to extract the IP address from it.
/sbin/ip addr show dev eth0 | grep 'inet'
Gets me as far as the correct line where the IP address is:
inet 10.1.4.33/22 brd 10.1.83.255 scope global eth0
And I need help extracting the IP address part 10.1.4.33

Pipe your output to grep -o:
/sbin/ip addr show dev eth0 | grep 'inet' | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n 1
The head -n 1 is required to select the first match only.

You can use this awk:
/sbin/ip addr show dev eth0 | awk -F '[ /\t]+' '$2=="inet"{print $3; exit}'
192.168.0.52

try one more approach in awk too.
/sbin/ip addr show dev eth0 | awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/);if(substr($0,RSTART,RLENGTH) && $0 ~ /inet/){print substr($0,RSTART,RLENGTH)}}'

For completion of the options available, using sed:
ip add show dev eth0 | sed -rn 's#^.*inet[[:blank:]]([[:digit:]]{1,3}(.[[:digit:]]{1,3}){3})/.*$#\1#p'

No complicated regular expression is needed.
output=$(/sbin/ip addr show dev eth0 | grep 'inet')
[[ $output = inet\ (.*)/ ]] && ip_addr=${BASH_REMATCH[1]}

Related

Get IP address info (gateway and subnet too) on Ubuntu or Debian using bash

I am trying to get the IP address of the ethernet or wifi adapter on Debian and Ubuntu systems using bash. I can get it reliably using ifconfig but it requires net-tools to be installed which is now deprecated but it does work.
showip=$(ifconfig eth0 | awk -F"[: ]+" '/inet addr:/ {print $4}')
I have made something using ip route but it doesn't work consistently, sometimes the outputted lines are different depending on the distro and version
MAINIP=$(ip route | awk 'NR==3{print $9}')
GATEWAYIP=$(ip route | awk 'NR==1{print $3}')
SUBNET=$(ip route | awk 'NR==2{print $1}')
Is there a way to grep or awk using regular expressions to ensure it works?
You could do:
MAINIP=$(ip addr show dev eth0 | grep "inet" | awk 'NR==1{print $2}' | cut -d'/' -f 1)
For subnet you could then:
SUBNET=$(ip route | grep "src $MAINIP" | awk '{print $1}')
And for GW:
GATEWAYIP=$(ip route show | grep default | awk '{print $3}')
Figured it out which works for wireless connections and not just eth0 (thank you #D.K.), only adjustment was for MAINIP. There may be an even better way or something I am overlooking though.
MAINIP=$(ip route | grep src | awk '{print $9}')
GATEWAYIP=$(ip route | grep default | awk '{print $3}')
SUBNET=$(ip route | grep proto | grep -v default | awk '{print $1}')
SUBNET without double grep
SUBNET=$(ip route | awk '/proto/ && !/default/ {print $1}')

Extracting MAC Address from arp table using grep regex

I am trying to extract MAC address from arp table without but it is returning a empty line.
I tried to use the command:
arp -a | grep eth1 | grep '^\A(([0-9a-fA-F]{2}):){5}([0-9a-fA-F]{2})$\z'
The 'arp -a' command return:
? (192.168.36.20) at 80:e0:1d:43:b0:60 [ether] on eth1
? (192.168.0.1) at 34:4b:50:b7:ef:08 [ether] on usb0
? (172.17.140.200) at 10:c3:7b:c4:82:04 [ether] on eth0
Thanks
Solved using:
arp -a | grep eth1 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
A much simpler way using awk:
$ arp | grep eth1 | awk '{print $3}'
See GNU Awk manual for more.

Isolate the last octet from an IP address and put it in a variable

The following script:
IP=`ifconfig en0 inet | grep inet | sed 's/.*inet *//; s/ .*//'`
isolates the IP address from ipconfig command and puts it into the variable $IP.
How can I now isolate the last octet from the said IP address and put it in a second variable - $CN
for instance:
$IP = 129.66.128.72 $CN = 72 or $IP = 129.66.128.133 $CN = 133...
Use "cut" command with . delimiter:
IP=129.66.128.72
CN=`echo $IP | cut -d . -f 4`
CN now contains the last octet.
In BASH you can use:
ip='129.66.128.72'
cn="${ip##*.}"
echo $cn
72
Or using sed for non BASH:
cn=`echo "$ip" | sed 's/^.*\.\([^.]*\)$/\1/'`
echo $cn
72
Using awk
cn=`echo "$ip" | awk -F '\\.' '{print $NF}'`
Shortcut:
read IP CN < <(exec ifconfig en0 | awk '/inet / { t = $2; sub(/.*[.]/, "", t); print $2, t }')
I would not use ifconfig to get the IP, rather use this solution, since it gets the IP needed to get to internet regardless of interface.
IP=$(ip route get 8.8.8.8 | awk '{print $NF;exit}')
and to get last octet:
last=$(awk -F. '{print $NF}' <<< $IP)
or get the last octet directly:
last=$(ip route get 8.8.8.8 | awk -F. '{print $NF;exit}')

Extracting IP address from a line from ifconfig output with grep

Given this specific line pulled from ifconfig, in my case:
inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.255
How could one extract the 192.168.2.13 part (the local IP address), presumably with regex?
Here's one way using grep:
line='inet 192.168.2.13 netmask 0xffffff00 broadcast 192.168.2.256'
echo "$line" | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
Results:
192.168.2.13
192.168.2.256
If you wish to select only valid addresses, you can use:
line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'
echo "$line" | grep -oE "\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
Results:
192.168.0.255
Otherwise, just select the fields you want using awk, for example:
line='inet 192.168.0.255 netmask 0xffffff00 broadcast 192.168.2.256'
echo "$line" | awk -v OFS="\n" '{ print $2, $NF }'
Results:
192.168.0.255
192.168.2.256
Addendum:
Word boundaries: \b
use this regex ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?=\s*netmask)
you can use egrep (which is basically the same as grep -E)
in egrep there are named groups for character classes, e.g.: "digit"
(which makes the command longer in this case - but you get the point...)
another thing that is good to know is that you can use brackets to repeat a pattern
ifconfig | egrep '([0-9]{1,3}\.){3}[0-9]{1,3}'
or
ifconfig | egrep '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'
if you only care about the actual IP address use the parameter -o to limit output to the matched pattern instead of the whole line:
ifconfig | egrep -o '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'
...and if you don't want BCast addresses and such you may use this grep:
ifconfig | egrep -o 'addr:([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' | egrep -o '[[:digit:]].*'
I assumed you were talking about IPv4 addresses only
Just to add some alternative way:
ip addr | grep -Po '(?!(inet 127.\d.\d.1))(inet \K(\d{1,3}\.){3}\d{1,3})'
it will print out all the IPs but the localhost one.
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}
I don't have enough reputation points to comment, but I found a bug in Steve's "select only valid addresses" regex. I don't quite understand the problem, but I believe I have found the fix. The first command demonstrates the bug; the second one demonstrates the fix:
$ echo "test this IP: 200.1.1.1" |grep -oE "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
$ echo "test this IP: 200.1.1.1" |grep -oE "\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
200.1.1.1
$
grep -oE "\b([0-9]{1,3}\.?){4}\b"
One way using sed. First instruction deletes all characters until first digit in the line, and second instruction saves first IP in group 1 (\1) and replaces all the line with it:
sed -e 's/^[^0-9]*//; s/\(\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\).*/\1/'
maybe this, one sed command, just for sports:
ip -o -4 addr show dev eth0 | sed 's/.* inet \([^/]*\).*/\1/'
This code works nicely and easy too.
ifconfig | grep Bcast > /tmp/ip1
cat /tmp/ip1 | awk '{ print $2 }' > /tmp/ip2
sed -i 's/addr://' /tmp/ip2
IPADDRESS=$(cat /tmp/ip2)
echo "$IPADDRESS"
This code works for me on raspberry pi zero w.
(extract wlan0: inet 192.168.x.y address from ifconfig output)
Search for pattern 'inet 192' in ifconfig output and get the 10th position using space delimiter.
$> ifconfig |grep 'inet 192'|cut -d' ' -f10
Output:
192.168.1.6
If using grep that supports Perl regex:
(your command that pulls mentioned line) | grep -Po 'inet \K[\d\.]+'

How do I find my computer's IP address using the bash shell?

Every now and again, I need to start the Django development server, and have it viewable by other machines on my network, as described here:
http://docs.djangoproject.com/en/dev/ref/django-admin/#runserver
My machine’s IP address tends to change every now and again, so I’d like to have a little shell alias or something that spits out the manage.py command with my machine’s current IP address, maybe like this:
python manage.py runserver $(COMMAND TO FIND MY MACHINE’S IP ADDRESS GOES HERE):8000
ifconfig en0 | grep inet | grep -v inet6
Output of above is expected to be in the following form:
inet 192.168.111.1 netmask 0xffffff00 broadcast 192.168.111.255
Add an awk statement to print the second column to avoid using cut (awk is a pretty standard unix tool):
ifconfig en0 | grep inet | grep -v inet6 | awk '{print $2}'
I use the following to get the current IP when on a LAN where the first few numbers of the IP are always the same (replace 192.168.111 with your own numbers):
ifconfig | grep 192.168.111 | awk '{print $2}'
To get the ip of another machine that you know the name of, try (replace hostname and 192.168.111 with your own values):
ping -c 1 hostname | grep 192.168.11 | grep 'bytes from' | awk '{print $4}' | sed 's/://g'
You might already be aware, but running
python manage.py runserver 0.0.0.0:8000
makes your machine visible to everyone on the network.
Is there a reason you'd need to specify your IP?
Thi should work as well as other commands I've already seen:
ifconfig eth0 | grep inet | awk '{print $2}' | cut -d':' -f2
Replace eth0 with the desired interface (eth0, eth1, wlan0...)
I̶ ̶t̶h̶i̶n̶k̶ ̶y̶o̶u̶ ̶c̶a̶n̶ ̶a̶l̶s̶o̶ ̶w̶r̶i̶t̶e̶:̶
̶ ̶ ̶ ̶h̶o̶s̶t̶n̶a̶m̶e̶ ̶-̶I̶ ̶|̶ ̶c̶u̶t̶ ̶-̶d̶'̶ ̶'̶ ̶-̶f̶1̶ ̶
The best solution would be to:
ifconfig | sed -n 's/.*inet addr:\([0-9.]\+\)\s.*/\1/p'
Folks are using character counts to pull the right columns from the ip address line, but using spaces as a delim makes this more scalable to different length ip addresses...
ifconfig en1 | grep inet | grep -v inet6 | cut -d" " -f2
This is a quick and dirty way, that works under OSX
/sbin/ifconfig | grep 'inet ' | grep -v '127.0.0.1' | head -n1 | awk '{print $2}'
Basically get all interfaces with an IPV4 address, skip localhost and then get the first interface.
Also, use path to ifconfig. I have seen to many shell script brake when used from ex. cron because of PATH failure.
On Mac OS X 10.11.6 El Capitan (and probably older releases), you can print your IP with
ipconfig getifaddr <device>
where <device> is en0, en1, etc.
http://osxdaily.com/2010/11/21/find-ip-address-mac/
ifconfig is probably what you're after. You'll need to either run it through grep to filter out some of the noise though.
The following command works perfectly for me on RHEL 6.3:
ifconfig | grep -v '127.0.0.1' | sed -n 's/.*inet addr:\([0-9.]\+\)\s.*/\1/p'
Simple Command to find IP Address with default interface.
ip -o route get "8.8.8.8" 2>/dev/null | sed -e 's/^.* src \([^ ]*\) .*$/\1/'
or
ip route | grep src | awk -F 'src' '{print $NF; exit}' | awk '{print $1}'
or
ip route | sed -n 's/.* src \(.*\) metric .*/\1/p' | uniq
Tested on All Unix OS
This may not be as elegant as some of the other solutions, but it works on Linux systems and is more comforting to look at than a regex:
ifconfig eth0 | grep 'inet addr:' | awk '{print $2}' | awk -F ':' '{print $2}'
Try this (if you are an Arch user)
resolveip -s $HOSTNAME
Alternative
For getting IPv4 adress you can use:
host $(uname -n) | grep "address" | grep -v "IPv6" | head -n 1 | awk '{print $4}'
For getting IPv6 one:
host $(uname -n) | grep "IPv6 address" | head -n 1 | awk '{print $5}'
You can replace $(uname -n) with $(hostname) if you'd like.
Here a solution to find the current IP address:
route -n get default|grep interface|awk ‘{ print $2 }’|xargs ipconfig getifaddr
tested on Mac only.
This checks your default interface, and use that to retrieve your primary ip.
Helpful when you have many interfaces, and tons of virtual ip addresses:
netstat -rn | gawk '/UG/ {print $NF}' | xargs ifconfig | gawk 'match($0,/inet addr:(.*) B/,a) {print a[1]}'
Recap: if you'd like to copy/paste to command line and just get the network IP address, here's what works on Mac (on WiFi):
echo $(ifconfig en0 | grep inet | grep -v inet6 | cut -d" " -f2)
Here is assigning it to bash script variable:
LOCAL_IP=$(ifconfig en0 | grep inet | grep -v inet6 | cut -d" " -f2)
This is based on answers by Valentin Rocher and Matt Kropmton
Tested on Archlinux only:
ifconfig $(route | awk '{if($1=="default") print $NF}') | awk '{if($1=="inet") print $2}'
Get the default interface with route, get the ip address of interface with ifconfig.
Because the command syntax or output may vary, you may need to change for works on your system.
On Android Shell, I'm tried:
ifconfig eth0 | grep 'inet addr' | tr -d '^[A-Za-z]+$' | tr -s ':' | cut -d ':' -f 2
On Ubuntu( and Debian like distro)
to see your local IP address:
hostname -I | awk '{print $1}'
to see your Global IP address:
curl -4 icanhazip.com
curl ifconfig.co //this responds faster
to see all information about your(or any)IP address:
whois $(curl ifconfig.co)
assumed you have installed whois on your machine, if it's not:
sudo apt-get install whois