How to use a variable in find command?
18,832
This will work:
filename="$F";
echo "$filename";
find . -name "$filename.txt" | while read fname; do
echo "$fname";
done;
Although you could just as easily do:
find . -name "$F.txt" | while read fname; do
echo "$fname";
done;
Double quotes (or no quotes at all) are necessary for variable expansion. Single quotes will not work.
Author by
nicusska
Updated on June 09, 2022Comments
-
nicusska almost 2 years
I am totally new in bash so sorry if my question is not well formatted or does not make sense :)
I'm trying to do something like that:
#..................... previous code where F is defining filename="$F"; echo "$filename"; find . -name ????? | while read fname; do echo "$fname"; done;
I want to use my variable $filename in find command (instead of ????), but I don't know how. I add some fixed value there for testing purpose, for example "abc.txt" (which exists and is stored in my variable), it works well, I just don't know how to use variable in find command.
Something like
find . -name '$filename.txt' | while read fname;
UPDATE: (I have 2 files (.xml and .txt) with the same name in folder)
find . -type f -name \*.xml | while read F; do something || echo $F; cat "$F"; #name without extenssion filename="${F%.*}"; echo "$filename"; find . -name "$filename.txt" | while read fname; do echo "$fname"; done; done;
-
anubhava over 8 years
find . -name "$filename.txt"
should work with variables in double quotes. -
ryanpcmcquen over 8 years@anubhava is correct, you must use double quotes for variables to expand.
-
Sleafar over 8 yearsWhat is the value of
$F
and what is the name of the file you are looking for? -
nicusska over 8 yearsI think there is problem somewhere else, I don't know this language, I just need to execute few commands, my code looks something like this -> I've put code to UPDATE in my question to be formatted.
-
-
Eric Renouf over 8 yearsyou only need the double quotes to help it safely expand (in case there are spaces etc.), the variables will expand without quotes as well--just not within single quotes
-
Alec about 6 yearsYou also need double quotes if use variable with ''. find . -name "${DB_NAME}some_text*.sh" find does not work with single quotes and does not return error.