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
1
  • This helped. Thanks!
    – nute11a
    Sep 21 '20 at 16:54
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 -- "${s}_"*.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.

2
  • 1
    Hmm... They would probably not want nullglob here. Think about what they want likely to do: change the filename suffix. set -- "${s}_"*.txt; mv "$1" "${1%.txt}.out"
    – Kusalananda
    Sep 21 '20 at 15:40
  • 1
    No it would error out, not being able to copy the file apple_*.txt. This would be reasonable.
    – Kusalananda
    Sep 21 '20 at 15:42

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