如何在 bash for 循环中迭代多个不连续的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25194635/
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 do I iterate over multiple, discontinuous ranges in a bash for loop
提问by MrMas
Note: I am NOT asking this question
注意:我不是在问这个问题
I looked for information on how to loop over a range of discontiguousnumbers such as 0,1,2,4,5,6,7,9,11 without having to put the numbers in by hand and still use the ranges.
我寻找有关如何循环一系列不连续数字(例如 0、1、2、4、5、6、7、9、11)而无需手动输入数字并仍然使用这些范围的信息。
The obvious way would be to do this:
显而易见的方法是这样做:
for i in 0 1 2 4 5 6 7 9 11; do echo $i; done
回答by Barmar
for i in {0..2} {4..6} {7..11..2}; do echo $i; done
See the documentation of bash Brace Expansion.
请参阅 bash Brace Expansion的文档。
回答by David C. Rankin
As others have noted, brace expansion
provides a way to select ranges, but you can also assign the results of multiple brace expansions to a variable using echo {..} {..}
. This may cut down on the typing in the body of the for
loop:
正如其他人所指出的,brace expansion
提供了一种选择范围的方法,但您也可以使用echo {..} {..}
. 这可能会减少for
循环体中的输入:
#!/bin/bash
range="`echo {2..6} {31..35} {50..100..10}`"
for i in $range; do echo $i; done
exit 0
output:
输出:
2
3
4
5
6
31
32
33
34
35
50
60
70
80
90
100
回答by Sodved
Edit: oops, didn't realise there were missing numbers.
编辑:哎呀,没有意识到缺少数字。
Updated: Define ranges and then use a while loop for each range. e.g.
更新:定义范围,然后对每个范围使用 while 循环。例如
ranges="0-2 4-7 9 11"
for range in $ranges
do
min=${range%-*}
max=${range#*-}
i=$min
while [ $i -le $max ]
do
echo $i
i=$(( $i + 1 ))
done
done
回答by wil93
for i in `cat file.txt`; do echo $i; done
where file.txt contains:
其中 file.txt 包含:
0
1
2
4
5
6
7
9
11