How would I delimit a string by multiple characters in bash. I want to get the first IP address.
inet addr:127.0.0.1 Mask:255.0.0.0
I would do this
echo "inet addr:127.0.0.1 Mask:255.0.0.0" | cut -d' ' -f2 | cut -d':' -f1
but I would like to combine the last two commands into one command.
I would like to get
127.0.0.1
With awk
, set the field delimiter as one or more space/tab or :
, and get the third field:
awk -F '[[:blank:]:]+' '{print $3}'
Note that, this would get the mentioned field delimiter separated third field, which may or may not be a valid IP address; from your attempt with cut
, i am assuming the input is consistent.
Example:
% awk -F '[[:blank:]:]+' '{print $3}' <<<'inet addr:127.0.0.1 Mask:255.0.0.0'
127.0.0.1
Set IFS to the delimiters:
echo inet addr:127.0.0.1 Mask:255.0.0.0 |
{ IFS=': ' read i a ip m e; echo $ip; }
This will set the variable i
to the string inet
, a
<- addr
, ip
<- 127.0.0.1
, m
<- Mask
, and e
<- 255.0.0.0
. Note that (in many shells) the variables are scoped and will lose their value outside of the braces. There are techniques available to give them global scope in shells which sensibly restrict their scope, such as:
IFS=': ' read i a ip m e << EOF
inet addr:127.0.0.1 Mask:255.0.0.0
EOF
echo $ip
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With