1

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!

1
  • Your problem is that you need to keep the related pairs related. A simple nested loop won't do that. You need arrays coupled by index (so a[x] matches b[x]) or, if the values are always integers and unique, b => a[b] (because bash has sparse arrays, so you can do that). Commented Jan 2, 2014 at 19:26

3 Answers 3

2
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

Sign up to request clarification or add additional context in comments.

Comments

2

...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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.