Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

arrays - Replace nested for loops in bash

can you help me getting rid off the nested for loop? Array may change all the time, as of right now i need to add/remove for loops. Is it possible with pure bash to replace nested for loops with more elegant solution?

#!/bin/bash

i=0
array=(A B C)
places=3
word1=word1
word2=word2
arrC=${#array[*]}
while [ $i -lt $((arrC**places)) ]; do
    for a in ${!array[*]}; do
        for b in ${!array[*]}; do
            for c in ${!array[*]}; do
                echo "[$i] ${array[$a]}${word1}${array[$b]}${word2}${array[$c]}"
                i=$((i + 1))
            done
        done
    done
done

I've made ABC array for simplicity. Here is more of a real example for an array: array=(I i L l | / 1 !)

question from:https://stackoverflow.com/questions/65842843/replace-nested-for-loops-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use recursion.

#! /bin/bash
array=(A B C)
words=(word1 word2)

combine () {
    local depth=$1
    local prefix=${2# }
    shift 2
    if ((depth == ${#array[@]})) ; then
        echo "$prefix"
        return
    fi

    local i
    for (( i=1; i<=$#; ++i )) ; do
        combine $((depth+1)) "$prefix${!i}${words[depth]}" "${array[@]}"
    done
}

combine 0 "" "${array[@]}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...