Capturing only a section of a command output
Using grep
ifconfig | grep -oP '(?<=inet addr:)[\d.]+'
This uses grep's Perl-style regular expressions to select the IP address that follows the string inet
.
So, to save that in a variable, just put both commands inside the $()
:
output=$(ifconfig | grep -oP '(?<=inet addr:)[\d.]+')
The above will save the IP addresses for all active interfaces on your system. If you just want to save the output for one interface, say eth0
, then use:
output=$(ifconfig eth0 | grep -oP '(?<=inet addr:)[\d.]+')
Using awk
ifconfig eth0 | awk -F'[ :]+' '/inet /{print $3}'
/inet /
selects lines that contain inet
. On those lines, the third field is printed where a field separator is an y combination of spaces or colons.
Using sed
ifconfig eth0 | sed -En 's/.*inet addr:([[:digit:].]+).*/\1/p'
Alternate ifconfig
There is another version of ifconfig
which produces output like inet 1.2.3.4
instead of inet addr:1.2.3.4
. For that version, try:
ifconfig | grep -oP '(?<=inet )[\d.]+'
Or:
ifconfig eth0 | awk '/inet /{print $2}'
Or, use this sed command which works with either version of ifconfig
:
ifconfig eth0 | sed -En 's/.*inet (addr:)?([[:digit:].]+).*/\2/p'
ifconfig might disappear in the future, it is deprecated in some linux (maybe some ubuntu versions, but read on).
ip from the iproute2 package (should be installed by default) gives
ip addr list
and can be abbreviated to
ip a
and combined with
ip a | grep -o -P '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}(?=/)'
to filter on all IPv4 look alike numbers with a following CIDR mask slash. If you don't mind about the broadcast, it even works in -E mode of grep, just leave the last brackets off the RegEx.
If you generally want to cut the cli output, and want to avoid piping it through cut ... (like in this example to get the first field)
IPS=$(ip a | grep -o -E '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' | cut -d\ -f1 - )
you could use bash string manipulation (like in the following example):
echo ${SSH_CONNECTION%% *}
This should give you a few clues where and how to start.