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
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
$()
: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:Using
awk
/inet /
selects lines that containinet
. On those lines, the third field is printed where a field separator is an y combination of spaces or colons.Using
sed
Alternate
ifconfig
There is another version of
ifconfig
which produces output likeinet 1.2.3.4
instead ofinet addr:1.2.3.4
. For that version, try:Or:
Or, use this sed command which works with either version of
ifconfig
: