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
Docker Command Can't Connect to Docker Daemon
Why Doesn't "Total" from Ls -L Add Up to Total File Sizes Listed
Append Date to Filename in Linux
How to Undo Strip - I.E. Add Symbols Back to Stripped Binary
Hardware Cache Events and Perf
Writing a Putchar in Assembly for X86_64 with 64 Bit Linux
Unit Testing for Shell Scripts
Linux: Command to Open Url in Default Browser
Cannot Connect to X Server :0.0 with a Qt Application
Udp-Broadcast on All Interfaces
How to Find the Java Sdk in Linux After Installing It
Crt1.O: in Function '_Start': - Undefined Reference to 'Main' in Linux
Find Matching Text and Replace Next Line
What Are the Rules for Valid Identifiers (E.G. Functions, Vars, etc) in Bash
Assembly: Printf Not Printing New Line