0

I'm trying to match specific individual strings together. For example, I'd like the following to be paired:

file1 and 123.jpg file2 and 432.jpg file3 and 345.jpg

Currently, I'm using the following inefficient method that matches all possibilities between the two lists:

declare -a name1=("file1" "file2" "file3")

declare -a name2=("123.jpg" "432.jpg" "345.jpg")

for y in "${name1[@]}"
do
  for x in "${name2[@]}"
  do
    echo $y$x
  done
done

This script provides the following output: file1123.jpg file1432.jpg file1345.jpg file2123.jpg file2432.jpg file2345.jpg file3123.jpg file3432.jpg file3345.jpg

How can I have only the desired pairs matched so that the output looks like the following: file1123.jpg file2432.jpg file3345.jpg

1 Answer 1

1

Indexed arrays are… indexed. :) Each element has an index (number). You want to pair 0th element of name1 with 0th element of name2, 1st with 1st etc.

Instead of looping over elements you need to loop over indices. ${#name1[@]} expands to the length of the array named name1. Let's denote this length N. If N is greater than 0 then indices are from 0 to N-1. The following snippet loops over the indices of name1:

#!/bin/bash

declare -a name1=("file1" "file2" "file3")
declare -a name2=("123.jpg" "432.jpg" "345.jpg")

for (( i=0; i<"${#name1[@]}"; i++ ))
do
    printf '%s\n' "${name1[i]}${name2[i]}"
done

Notes:

  • printf is better than echo.
  • variables should be double-quoted unless you really know you don't want them quoted.
  • The code loops over the indices of name1. If name2 is shorter then any missing element will expand to an empty string. If name2 is longer then excessive elements will not be retrieved.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .