bash 如何在bash中使用步骤n生成范围?(生成带有增量的数字序列)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/966020/
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
How to produce a range with step n in bash? (generate a sequence of numbers with increments)
提问by SilentGhost
The way to iterate over a range in bash is
在 bash 中迭代范围的方法是
for i in {0..10}; do echo $i; done
What would be the syntax for iterating over the sequence with a step? Say, I would like to get only even number in the above example.
用一个步骤迭代序列的语法是什么?说,我想在上面的例子中只得到偶数。
回答by chaos
I'd do
我会做
for i in `seq 0 2 10`; do echo $i; done
(though of course seq 0 2 10
will produce the same output on its own).
(虽然当然seq 0 2 10
会自己产生相同的输出)。
Note that seq
allows floating-point numbers (e.g., seq .5 .25 3.5
) but bash's brace expansion only allows integers.
请注意,seq
允许浮点数(例如,seq .5 .25 3.5
),但 bash 的大括号扩展只允许整数。
回答by TheBonsai
Bash 4's brace expansion has a step feature:
Bash 4的大括号扩展有一个 step 特性:
for {0..10..2}; do
..
done
No matter if Bash 2/3 (C-style for loop, see answers above) or Bash 4, I would prefer anything over the 'seq' command.
无论是 Bash 2/3(C 风格的 for 循环,参见上面的答案)还是 Bash 4,我都喜欢使用 'seq' 命令。
回答by Fritz G. Mehner
Pure Bash, without an extra process:
纯 Bash,没有额外的过程:
for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
echo $COUNTER
done
回答by z -
#!/bin/bash
for i in $(seq 1 2 10)
do
echo "skip by 2 value $i"
done
回答by Mir-Ismaili
> seq 4
1
2
3
4
> seq 2 5
2
3
4
5
> seq 4 2 12
4
6
8
10
12
> seq -w 4 2 12
04
06
08
10
12
> seq -s, 4 2 12
4,6,8,10,12