多個變量我有被下面生成的字符串:字符串分割到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