I want to loop through all files matching a pattern of the form

for file in {prefix1, prefix2, ...}*{postfix1, postfix2, ...}; do

How can I programmatically replace {prefix1, prefix2, ...} with a list containing these names? I tried $prefix*$postfix with prefix={prefix1,prefix2,...} but it doesn't work because the brace expansion is done before the variable expansion.

  • Can you provide an example of the input files and the expected output? – Paulo Tomé Feb 12 at 11:16

If the prefix/suffix patterns don't contain spaces, it's possible to use extended globbing:

shopt -s extglob

echo $prefix*$suffix

for file in $prefix*$suffix; do
  • Can handle spaces if the variable IFS is set appropriately
| improve this answer | |

One way to do it is to use two loops combined with bash arrays, something like this:

foo=(one two three)
bar=(four five six)
for f in ${foo[@]}; do 
  for g in ${bar[@]}; do
    echo $f$g
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.