7

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

find /script -name '*file_topicv*'
/script/VER_file_topicv_32.2.212.1

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

var=file_topicv

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.


Update:

I think this is the problem:

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

echo $var
generateFMN

ls  /script/VERSIONS | grep "$var"

NO OUTPUT

var=generateFMN
 ls  /script/VERSIONS | grep "$var"
VER_generateFMN_32.2.212.1

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

agc
  • 7,223
yael
  • 13,106

1 Answers1

12

The first double-quoted one should work:

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

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*'
./asdfghjkl

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*".

ilkkachu
  • 138,973
  • 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: https://unix.stackexchange.com/questions/417756/variable-printed-the-same-value-but-actually-value-is-diff – ilkkachu Jan 17 '18 at 15:27