Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I delimit a string by multiple delimiters in bash

Tags:

bash

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

like image 291
richard_d_sim Avatar asked Mar 08 '17 02:03

richard_d_sim


2 Answers

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
like image 58
heemayl Avatar answered Oct 13 '22 07:10

heemayl


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
like image 37
William Pursell Avatar answered Oct 13 '22 07:10

William Pursell