Ubuntu – Capturing only a section of a command output

bashcommand linescripts

If I were to type a certain command, it would give me a long output in the terminal. I only need a few characters of this output. How do I, in a bash script, save only certain characters from a terminal output as a variable?

For example, if my script is:

#!/bin/bash

ifconfig

I could save the whole output as a variable using

OUTPUT="$(ifconfig)"

But I only want my IP address copied, which is after inet [IP ADDRESS]

How would I go about doing this?

Edit: IP Address is just being used here as an example as I cannnot mention the command on here for security reasons, it's actually 'phrase: [five digit number]' in amongst other text and I just need that five digit number. Sorry for any confusion

Best Answer

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'