1

These are my sample files

user@linux:~$ ls -l | cut -d ' ' -f 10-

01. old Name.txt
02. old Name.txt
03. old Name.txt
test.txt
user@linux:~$ 

This is what I want to do.

user@linux:~$ for output in *'old Name'*; do echo $output; done
01. old Name.txt
02. old Name.txt
03. old Name.txt
user@linux:~$ 

Since the actual code is using old Name multiple times, so I would like to put this on variable.

So, linux command in this case is *'old Name'*

Attempt 1 doesn't work, so I tried different way

user@linux:~$ cmd='old Name'
user@linux:~$ for output in $cmd; do echo $output; done
old
Name
user@linux:~$ 

Attempt 2

cmd="*'old Name'*""
for output in $cmd; do echo $output; done

However, it doesn't work

user@linux:~$ cmd="*'old Name'*""
> for output in $cmd; do echo $output; done
> 
> 

Attempt 3

cmd='old Name'
for output in ${*'cmd'*}; do echo $output; done

Also doesn't work

cmd='old Name'
user@linux:~$ for output in ${*'cmd'*}; do echo $output; done
bash: ${*'cmd'*}: bad substitution
user@linux:~$ 

Let me know if you need more info.

  • 1
    for output in *"$cmd"* – muru Dec 15 '19 at 3:10
1

You have the loop

for filename in *'old Name'*; do
    echo "$filename"
done

and you want to change the pattern *'old Name'* so that the string old Name is kept in a variable.

This can be done with

name='old Name'

for filename in *"$name"*; do
    echo "$filename"
done

or just

printf '%s\n' *"$name"*

To have the pattern work correctly, the parts of the pattern that contain filename globbing wildcards must stay unquoted. The * characters can't therefore be part of the name variable's value if we quote $name. If they were, they would be used as literal * characters, not as wildcards.

At the same time, we don't want to use the name variable unquoted, as that would break it apart into two words on the space, and you'd end up with two separate patterns.

This is why setting name to the string old Name and the using *"$name"* in the loop, as shown above, would probably be the best solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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