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.