richard_d_sim
richard_d_sim

Reputation: 913

How would I delimit a string by multiple delimiters in 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

Upvotes: 6

Views: 10506

Answers (2)

William Pursell
William Pursell

Reputation: 212414

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

Upvotes: 2

heemayl
heemayl

Reputation: 42087

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

Upvotes: 4

Related Questions