Linux Bash Script to Extract Ip Address

Linux bash script to extract IP address

To just get your IP address:

echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'`

This will give you the IP address of eth0.

Edit: Due to name changes of interfaces in recent versions of Ubuntu, this doesn't work anymore. Instead, you could just use this:

hostname --all-ip-addresses or hostname -I, which does the same thing (gives you ALL IP addresses of the host).

How do you extract IP addresses from files using a regex in a linux shell?

You could use grep to pull them out.

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' file.txt

extract ip address from variable string


ip=$(last -i | head -n 1 | awk '{print $3}')

Update:

ip=$(last -i | grep -Pom 1 '[0-9.]{7,15}')

Using Bash to Extract IP Addresses From Each Line of Log File

To print IPs next to each other, try the below command:

cat first | grep -o '[0-9]\{0,3\}\.[0-9]\{0,3\}\.[0-9]\{0,3\}\.[0-9]\{0,3\}' | awk 'NR%2{printf $0"\t";next;}1' 

extract ip address from variable string


ip=$(last -i | head -n 1 | awk '{print $3}')

Update:

ip=$(last -i | grep -Pom 1 '[0-9.]{7,15}')

using bash with sed how to extract ip from a hostname command and saving it in /etc/hosts file

Your logic is good, but you don't use the correct pattern in your string substitution. You should have written the following :

ip=$(hostname -I | cut -d ' ' -f1); echo "$ip ip-${ip//[.:]/-}" >> /etc/hosts


Related Topics



Leave a reply



Submit