I am searching for files by finding a partial file name:

find /script -name '*file_topicv*'

It works, but not when the partial file name is a variable:


find reported file not found, (in spite of the file existing):

find /script -name '*$var*'

What is wrong here?

I also tried these:

find /script -name "*$var*"
find /script -name "*\$var*"
find /script -name "*\\$var*"

but not one of those works.


I think this is the problem:

var=` find /tmp -name '*.xml' -exec sed -n 's/<Name>\([^<]*\)<\/Name>/\1/p' {} +  |  xargs `

echo $var

ls  /script/VERSIONS | grep "$var"


 ls  /script/VERSIONS | grep "$var"

So why $var from find command cause the problem? (I removed the spaces by xargs.)


The first double-quoted one should work:

$ touch asdfghjkl
$ var=fgh
$ find -name "*$var*"

Within single quotes ('*$var*'), the variable is not expanded, and neither is it expanded when the dollar sign is escaped in double quotes ("*\$var*"). If you double-escape the dollar sign ("*\\$var*"), the variable is expanded but find gets a literal backslash, too. (But find seems to take the backslash as an escape again, so it doesn't change the meaning.)

So, confusing though as it is, this also works:

$ set -x
$ find -name "*\\$var*"
+ find -name '*\fgh*'

You can try to run all the others with set -x enabled to see what arguments find actually gets.

As usual, wrap the variable name in braces {}, if it's to be followed by letters, digits or underscores, e.g. "*${prefix}somename*".

  • 1
    the first double-quoted one also works for me. btw, worth mentioning that it will sometimes be necessary to use ${var} rather than just $var inside the double-quotes, depending on what comes after the variable....a * is fine, a letter/digit/underscore/etc is not. – cas Jan 17 '18 at 10:34
  • see my update , this is the problem , when $var comes from find & this isnt works – yael Jan 17 '18 at 10:47
  • @yael It still works for me with var=$(find ...). The problem seems to be that something is adding a carriage-return \r to the string. Or maybe it's in the input XML file already (maybe try grep '<Name>' yourxmlfile | hexdump -C and see if there's n 0D byte in there). – cas Jan 17 '18 at 14:58
  • @cas, they almost certainly have a CR in there, the sed here won't remove it or any other trailing garbage on the line. yael posted another question on it: unix.stackexchange.com/questions/417756/… – ilkkachu Jan 17 '18 at 15:27

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.