Bash:如何拆分字符串并分配多个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33320584/
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
Bash: How to split a string and assign multiple variables
提问by kuruvi
I have to split a URL string and assign variables to few of the splits. Here is the string
我必须拆分 URL 字符串并将变量分配给少数拆分。这是字符串
http://web.com/sub1/sub2/sub3/sub4/sub5/sub6
I want to assign variables like below from bash
我想从 bash 分配如下变量
var1=sub2
var2=sub4
var3=sub5
How to do this in bash?
如何在 bash 中做到这一点?
回答by Cyrus
x="http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"
IFS="/" read -r foo foo foo foo var1 foo var2 var3 foo <<< "$x"
echo "$var1 $var2 $var3"
Output:
输出:
sub2 sub4 sub5
Or with an array:
或者使用数组:
x="http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"
IFS="/" read -r -a var <<< "$x"
echo "${var[4]}"
declare -p var
Output:
输出:
sub2 declare -a var='([0]="http:" [1]="" [2]="web.com" [3]="sub1" [4]="sub2" [5]="sub3" [6]="sub4" [7]="sub5" [8]="sub6")'
From man bash
:
来自man bash
:
IFS
: The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command.
IFS
:内部字段分隔符,用于扩展后的分词,并使用 read 内置命令将行拆分为单词。
回答by Peter Cordes
This should work:
这应该有效:
IFS=/ read -r proto host dummy var1 dummy var2 var3 dummy <<< "$url"
Or read -ra
to read into an array. read -r
makes backslash non-special.
或者read -ra
读入一个数组。 read -r
使反斜杠非特殊。
This won't work in bash:
这在 bash 中不起作用:
echo "$url" | read ...
because read
would run in a subshell, so the variables wouldn't be set in the parent shell.
因为read
会在子 shell 中运行,所以不会在父 shell 中设置变量。
回答by Thejaswi
I think a better solution would be to assign the result of splitting into an array. For example:
我认为更好的解决方案是将拆分的结果分配到数组中。例如:
IFS='/' read -a array <<< "http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"
Unfortunately, this will create 3 'extraneous' elements, which you will have to take care of!
不幸的是,这将创建 3 个“无关”元素,您必须处理这些元素!
echo ${array[*]}
http: web.com sub1 sub2 sub3 sub4 sub5 sub6
EDIT: In here ${array[1]} is an empty element!
编辑:在这里 ${array[1]} 是一个空元素!