多个变量我有被下面生成的字符串:字符串分割到Bash中
192.168.1.1,UPDOWN,Line protocol on Interface GigabitEthernet1/0/13, changed state to up
我如何可以采取的字符串(使用bash)让2个变量出来的吗?
比如我想
$ip=192.168.1.1
$int=GigabitEthernet1/0/13
多个变量我有被下面生成的字符串:字符串分割到Bash中
192.168.1.1,UPDOWN,Line protocol on Interface GigabitEthernet1/0/13, changed state to up
我如何可以采取的字符串(使用bash)让2个变量出来的吗?
比如我想
$ip=192.168.1.1
$int=GigabitEthernet1/0/13
尝试这种情况:
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]}"
在此脚本${myarray[0]}
是指在逗号分隔的字符串的第一场,${myarray[1]}
指第二字段在逗号分隔的字符串等
使用read
与自定义字段分隔符(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
确保将字符串括在引号。
如何将字符串拆分为一个数组变量? – Inoperable
@Inoperable http://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash – damienfrancois
@damienfrancois有最佳答案。您还可以使用bash的正则表达式匹配:
if [[ $string =~ ([^,]+).*"Interface "([^,]+) ]]; then
ip=${BASH_REMATCH[1]}
int=${BASH_REMATCH[2]}
fi
echo $ip; echo $int
192.168.1.1
GigabitEthernet1/0/13
使用bash的正则表达式,任意文字可以被引用(必须是,如果有空格),但正则表达式metachars不能被引用。
我会在这里指出我在我现在删除的冗余答案中所说的:正则表达式可能在这种情况下,并不比字符串分割好得多,但可以用于其他问题。 – chepner
'GigabitEthernet1/0/13'如何分隔?无论接口'? –
是的。无论如何界面 – l0sts0ck