31

I have a string that gets generated below:

192.168.1.1,UPDOWN,Line protocol on Interface GigabitEthernet1/0/13, changed state to up

How can I take that string and make 2 variables out of it (using bash)?

For example I want

$ip=192.168.1.1 
$int=GigabitEthernet1/0/13
2
  • How is GigabitEthernet1/0/13 delimited? Whatever follows Interface<space>? Commented May 14, 2014 at 20:00
  • Yes. Whatever follows Interface Commented May 14, 2014 at 20:01

3 Answers 3

51

Try this:

mystring="192.168.1.1,UPDOWN,Line protocol on Interface GigabitEthernet1/0/13, changed state to up"

IFS=',' read -a myarray <<< "$mystring"

echo "IP: ${myarray[0]}"
echo "STATUS: ${myarray[3]}"

In this script ${myarray[0]} refers to the first field in the comma-separated string, ${myarray[1]} refers to the second field in the comma-separated string, etc.

Sign up to request clarification or add additional context in comments.

Comments

27

Use read with a custom field separator (IFS=,):

$ IFS=, read ip state int change <<< "192.168.1.1,UPDOWN,Line protocol on Interface GigabitEthernet1013, changed state to up"
$ echo $ip
192.168.1.1
$ echo ${int##*Interface}
GigabitEthernet1013

Make sure to enclose the string in quotes.

2 Comments

how do I split a string into one array variable?
8

@damienfrancois has the best answer. You can also use bash regex matching:

if [[ $string =~ ([^,]+).*"Interface "([^,]+) ]]; then 
    ip=${BASH_REMATCH[1]}
    int=${BASH_REMATCH[2]}
fi
echo $ip; echo $int
192.168.1.1
GigabitEthernet1/0/13

With bash regexes, any literal text can be quoted (must be, if there's whitespace), but the regex metachars must not be quoted.

1 Comment

I'll point out here what I said in my now-deleted redundant answer: a regular expression may not be that much better than string splitting in this case, but can be useful for other problems.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.