3

I'm trying to loop through several files with this naming structure: apple_123.txt, orange_456.txt, banana_789.txt

I'm trying to use a wildcard for the numbers, but the wildcard is not expanded and the output looks like this: apple_*.txt

I've tried quoting around the wildcard but it didn't make a difference.

My loop:

fruit=(apple, orange, banana)
for f in "${fruit[@]}"
do
        echo "mv ${f}_*.txt ${f}_*.out"
done
jesse_b
  • 37,005
nute11a
  • 33

1 Answers1

2

File globbing is not performed inside double quotes (or single quotes for that matter).

You could change it to:

fruit=(apple orange banana)
for f in "${fruit[@]}"
do
        set -- "${f}_"*.txt
        mv "$1" "${1%.txt}.out"
done

Since file globbing won't take place inside quotes this is a bit tricky and thanks to a suggestion from Kusalananda I've used the set builtin here to perform the globbing on the file and set it as a positional parameter that we can then use to perform the extension manipulations on. If there is a possibility of multiple matching files this script can be modified with either the rename utility or another nested loop to operate on all of them, otherwise as is this will only rename the first match.

In your current version, if the .out file doesn't already exist or if there are multiple matches this script will not work the way you want it to. If you simply want to change the extension but retain the number you can use shell parameter expansion to simply strip the .txt and then add .out.

Additionally there is no need to use the commas in your array declaration, the elements will be split by whitespace. That is unless your filenames actually contain the literal comma character.

jesse_b
  • 37,005