Olivier Gérault
Olivier Gérault

Reputation: 61

filename contains space and wildcard in a variable

I receive files which names contain spaces and change every week (the name contains the week number)

IE, the file for this week looks like This is the file - w37.csv

I have to write a script to take this file into account. I didn't succeed in writing this script.

If I do :

    $FILE="This is the file - w*.csv"

I don't find /dir/${FILE}

I tried "This\ is\ the\ file - w*.csv"

I tried /dir/"${FILE}" and "/dir/${FILE}"

But I still can't find my file

It looks like the space in the name needs the variable to be double-quoted but, then, the wildcard is not analysed.

Do you have an idea (or THE answer)?

Regards,

Olivier

Upvotes: 5

Views: 6439

Answers (3)

chepner
chepner

Reputation: 531135

Use a bash array

v=( /dir/This\ is\ the\ file - w*.csv )

If there is guaranteed to be only one matching file, you can just expand $v. Otherwise, you can get the full list of matching files by expanding as

"${v[@]}"

or individual matches using

"${v[0]", "${v[1]}", etc

Upvotes: 3

choroba
choroba

Reputation: 241858

First of all, you should not use the dollar sign in an assignment.

Moreover, wildcard expansion is not called in an assignment. You can use process substitution for example, though:

FILE=$(echo 'This is the file - w'*.csv)

Note that the wildcard itself is not included in the quotes. Quotes prevent wildcard expansion.

Upvotes: 1

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143081

echo /dir/"This is the file - w"*.csv

or — you almost tried that —

echo /dir/This\ is\ the\ file\ -\ w*.csv

Upvotes: 5

Related Questions