bash - 用于 IP 范围的循环,不包括某些 IP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30812197/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:12:06  来源:igfitidea点击:

bash - for loop for IP range excluding certain IPs

bashfor-loopipip-address

提问by spacemtn5

I have the below for loop

我有以下 for 循环

for ip in 10.11.{32..47}.{0..255}
do
        echo "<ip>${ip}</ip>" 
done

I want to exclude this iprange: 10.11.{32..35}.{39..61}from the above for loop. This ip range is a subset of the above one. Is there a way to do that?

我想10.11.{32..35}.{39..61}从上面的 for 循环中排除这个 iprange: 。此 ip 范围是上述范围的一个子集。有没有办法做到这一点?

I tried this, this doesn't work:

我试过这个,这不起作用:

abc=10.11.{34..37}.{39..61}
for ip in 10.11.{32..47}.{0..255}
do
    if [[ $ip == $abc ]]
    then
            echo "not_defined"
    else
            echo "<ip>${ip}</ip>"
    fi
done

回答by Alfe

Try this:

尝试这个:

for ip in 10.11.{32..47}.{0..255}
do
        echo 10.11.{32..35}.{39..61} | grep -q "\<$ip\>" && continue
        echo "<ip>${ip}</ip>" 
done

This of course is a simple solution which still loops through the complete set and throws away some unwanted elements. As your comment suggests, this may produce unnecessary delays during the parts which are skipped. To avoid these, you can generate the values in parallel to the processing like this:

这当然是一个简单的解决方案,它仍然遍历整个集合并丢弃一些不需要的元素。正如您的评论所暗示的那样,这可能会在跳过的部分期间产生不必要的延迟。为了避免这些,您可以像这样在处理的同时生成值:

for ip in 10.11.{32..47}.{0..255}
do
        echo 10.11.{32..35}.{39..61} | grep -q "\<$ip\>" && continue
        echo "${ip}" 
done | while read ip
do
        process "$ip"
done

If the process "$ip"is taking at least a minimal amount of time, then the time for the generation of the values will most likely not fall into account anymore.

如果process "$ip"至少花费最少的时间,那么很可能不再考虑生成值的时间。

If you want to skip the values completely, you also can use a more complex term for your IPs (but then it will not be clear anymore how this code derived from the spec you gave in your question, so I better comment it thoroughly):

如果你想完全跳过这些值,你也可以为你的 IP 使用一个更复杂的术语(但是,这段代码是如何从你在问题中给出的规范派生出来的就不再清楚了,所以我最好彻底评论一下):

# ranges below result in
# 10.11.{32..47}.{0..255} without 10.11.{32..35}.{39..61}:
for ip in 10.11.{32..35}.{{0..38},{62..255}} 10.11.{36..47}.{0..255}
do
        echo "${ip}" 
done

回答by Cyrus

Try this:

尝试这个:

printf "%s\n" 10.11.{32..47}.{0..255} 10.11.{32..35}.{39..61} | sort | uniq -u | while read ip; do echo $ip; done