bash Shell 脚本按空格分割字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38979322/
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
Shell script split a string by space
提问by Jes
The bash shell script can split a given string by space into a 1D array.
bash shell 脚本可以将给定的字符串按空格拆分为一维数组。
str="a b c d e"
arr=($str)
# arr[0] is a, arr[1] is b, etc. arr is now an array, but what is the magic behind?
But, what exactly happened when we can arr=($str)
? My understanding is the parenthesis here creates a subshell, but what happen after that?
但是,当我们可以的时候究竟发生了什么arr=($str)
?我的理解是这里的括号创建了一个子shell,但之后会发生什么?
回答by chepner
In an assignment, the parentheses simply indicate that an array is being created; this is independent of the use of parentheses as a compound command.
在赋值中,括号只是表示正在创建一个数组;这与括号作为复合命令的使用无关。
This isn't the recommended way to split a string, though. Suppose you have the string
但是,这不是拆分字符串的推荐方法。假设你有字符串
str="a * b"
arr=($str)
When $str
is expanded, the value undergoes both word-splitting (which is what allows the array to have multiple elements) and pathname expansion. Your array will now have a
as its first element, b
as its last element, but one or more elements in between, depending on how many files in the current working directly *
matches. A better solution is to use the read
command.
当$str
膨胀时,值既经历字分裂(这是允许阵列具有多个元素)和路径扩展。您的数组现在将a
作为它的第一个元素,b
作为它的最后一个元素,但中间有一个或多个元素,具体取决于当前工作中直接*
匹配的文件数量。更好的解决方案是使用该read
命令。
read -ra arr <<< "$str"
Now the read
command itself splits the value of $str
without also applying pathname expansion to the result.
现在,read
命令本身会拆分 的值,$str
而不会对结果应用路径名扩展。
回答by sjsam
It seems you've confused
看来你糊涂了
arr=($str) # An array is created with word-splitted str
with
和
(some command) # executing some command in a subshell
Note that
注意
arr=($str)
is different from arr=("$str")
in that in the latter, the double quotes prevents word splitting ie the array will contain only one value -> a b c d e
.
arr=($str)
不同于arr=("$str")
在于:在后者中,双引号防止字分裂即阵列将仅包含一个值- > a b c d e
。
You can check the difference between the two by the below
您可以通过以下方式检查两者之间的区别
echo "${#arr[@]}"