filename contains space and wildcard in a variable

折月煮酒 提交于 2019-11-30 20:52:53

问题


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


回答1:


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

or — you almost tried that —

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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/12456562/filename-contains-space-and-wildcard-in-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!