0

I have a script in which I am attempting to match strings in filenames on either side of a word. The keywords which are meant for pattern matchin with the wildcard character, as in:

ls *spin*.txt

This will of course match any of the following filenames:

one_spin.txt 4_5342spin-yyy.txt fifty_spinout.txt

...etc.

What I would like to do is use the word 'spin' and a number of other words as match cases in an array that I can pass through a loop. I'd like these matches to be case-insensitive I attempt this like so:

types=(spin wheel rotation)

for file in $types; do
    ls '*'${file}'*.txt'
done

EDIT: Because I'm looking for a solution that is maleable, I'd also like to be able to do something like:

types=(spin wheel rotation)

for file in $types; do
    find . -iname "*$file*.txt"
done

I'm not sure how bash interprets either of these except seeing that it does not list the desired files. Can someone clarify what is happening in my script, and offer a solution that meets the aforementioned criteria?

2 Answers 2

2

Your attempt will work with a little more tweaks. As you are assigning types as an array, you need to access it as an array.
Would you please try:

types=(spin wheel rotation)

for file in "${types[@]}"; do
    ls *${file}*.txt
done

If your bash supports shopt builtin, you can also say:

shopt -s extglob
ls *@(spin|wheel|rotation)*.txt

If you want to make it match in a case-insensitive way, please try:

shopt -s extglob nocaseglob
ls *@(spin|wheel|rotation)*.txt

which will match one_Spin.txt, fifty_SPINOUT.TXT, etc.

Hope this helps.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you - I need to study the shopt built-in. I'd seen the extglob option and I don't fully understand what it affords a .sh script, pattern-wise. Found a decent overview here: riptutorial.com/bash/example/13126/extended-globbing
what if I want to match and have it be case-insensitive? Something like echo find . -iname *${file}*.txt
Thank you for the prompt feedback. Surely find . -iname "*$file*.txt" does work. you can also make use of shopt -s nocaseglob as well. Please take a look of my updated answer. BR.
0

don't make it complicate please try this instead

ls *{spin,wheel,rotation}*.txt

This also helpfull in creating files

touch 1_{spin,wheel,rotation,ads,sad,zxc}_2.txt

Or dirs

mkdir -p {test,test2/log,test3}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.