user3154807
user3154807

Reputation: 11

Bash For loop - multiple variables, not using arrays?

I have run into an issue that seems like it should have an easy answer, but I keep hitting walls.

I'm trying to create a directory structure that contains files that are named via two different variables. For example:

101_2465
203_9746
526_2098

I am looking for something that would look something like this:

for NUM1 in 101 203 526 && NUM2 in 2465 9746 2098
do
mkdir $NUM1_$NUM2
done

I thought about just setting the values of NUM1 and NUM2 into arrays, but it overcomplicated the script -- I have to keep each line of code as simple as possible, as it is being used by people who don't know much about coding. They are already familiar with a for loop set up using the example above (but only using 1 variable), so I'm trying to keep it as close to that as possible.

Thanks in advance!

Upvotes: 1

Views: 155

Answers (3)

Gavin Smith
Gavin Smith

Reputation: 3154

One way is to separate the entries in your two variables by newlines, and then use paste to get them together:

a='101 203 526'
b='2465 9746 2098'

# Convert space-separated lists into newline-separated lists 
a="$(echo $a | sed 's/ /\n/g')"
b="$(echo $b | sed 's/ /\n/g')"

# Acquire newline-separated list of tab-separated pairs
pairs="$(paste <(echo "$a") <(echo "$b"))"


# Loop over lines in $pairs

IFS='
'

for p in $pairs; do
echo "$p" | awk '{print $1 "_" $2}'
done

Output:

101_2465
203_9746
526_2098

Upvotes: 0

Dmitry Alexandrov
Dmitry Alexandrov

Reputation: 1773

...setting the values of NUM1 and NUM2 into arrays, but it overcomplicated the script...

No-no-no. Everything will be more complicated, than arrays.

NUM1=( 101 203 526 )
NUM2=( 2465 9746 2098 )
for (( i=0; i<${#NUM1}; i++ )); do
    echo ${NUM1[$i]}_${NUM2[$i]}
done

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246754

while read NUM1 NUM2; do
    mkdir ${NUM1}_$NUM2
done << END
101 2465
203 9746
526 2098
END

Note that underscore is a valid variable name character, so you need to use braces to disambiguate the name NUM1 from the underscore

Upvotes: 2

Related Questions