bash 用bash中的数字序列创建一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39267836/
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
Create an array with a sequence of numbers in bash
提问by jarhead
I would like to write a script that will create me an array with the following values:
我想编写一个脚本,该脚本将为我创建一个具有以下值的数组:
{0.1 0.2 0.3 ... 2.5}
Until now I was using a script as follows:
到目前为止,我使用的脚本如下:
plist=(0.1 0.2 0.3 0.4)
for i in ${plist[@]}; do
echo "submit a simulation with this parameter:"
echo "$i"
done
But now I need the list to be much longer ( but still with constant intervals).
但是现在我需要更长的列表(但仍然具有恒定的间隔)。
Is there a way to create such an array in a single command? what is the most efficient way to create such a list?
有没有办法在单个命令中创建这样的数组?创建此类列表的最有效方法是什么?
回答by fedorqui 'SO stop harming'
Using seq
you can say seq FIRST STEP LAST
. In your case:
使用seq
你可以说seq FIRST STEP LAST
。在你的情况下:
seq 0 0.1 2.5
Then it is a matter of storing these values in an array:
然后是将这些值存储在数组中的问题:
vals=($(seq 0 0.1 2.5))
You can then check the values with:
然后,您可以使用以下方法检查值:
$ printf "%s\n" "${vals[@]}"
0,0
0,1
0,2
...
2,3
2,4
2,5
Yes, my locale is set to have commas instead of dots for decimals. This can be changed setting LC_NUMERIC="en_US.UTF-8"
.
是的,我的语言环境设置为逗号而不是小数点。这可以更改设置LC_NUMERIC="en_US.UTF-8"
。
By the way, brace expansionalso allows to set an increment. The problem is that it has to be an integer:
顺便说一下,大括号扩展也允许设置增量。问题是它必须是一个整数:
$ echo {0..15..3}
0 3 6 9 12 15
回答by Amir Mehler
Bash supports C style For loops:
Bash 支持 C 风格的 For 循环:
$ for ((i=1;i<5;i+=1)); do echo "0.${i}" ; done
0.1
0.2
0.3
0.4
回答by ePi272314
Complementing the main answer
补充主要答案
In my case, seq
was not the best choice.
To produce a sequence, you can also use the jot
utility. However, this command has a more elaborated syntaxis.
就我而言,seq
这不是最佳选择。
要生成序列,您还可以使用该jot
实用程序。但是,此命令具有更详细的语法。
# 1 2 3 4
jot - 1 4
# 3 evenly distributed numbers between 0 and 10
# 0 5 10
jot 3 0 10
# a b c ... z
jot -c - 97 122