在 Bash 中将字符串拆分为多个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23663963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split string into multiple variables in Bash
提问by l0sts0ck
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)?
如何获取该字符串并从中生成 2 个变量(使用 bash)?
For example I want
例如我想要
$ip=192.168.1.1
$int=GigabitEthernet1/0/13
回答by Helio
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 firstfield in the comma-separated string, ${myarray[1]}
refers to the secondfield in the comma-separated string, etc.
在此脚本中,${myarray[0]}
指的是逗号分隔字符串中的第一个字段,${myarray[1]}
指的是逗号分隔字符串中的第二个字段,以此类推。
回答by damienfrancois
Use read
with a custom field separator (IFS=,
):
使用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
Make sure to enclose the string in quotes.
确保将字符串括在引号中。
回答by glenn Hymanman
@damienfrancois has the best answer. You can also use bash regex matching:
@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
With bash regexes, any literal text can be quoted (must be, if there's whitespace), but the regex metachars must not be quoted.
使用 bash 正则表达式,可以引用任何文字文本(必须是,如果有空格),但不能引用正则表达式元字符。