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.

Share:
18,832
nicusska
Author by

nicusska

Updated on June 09, 2022

Comments

  • nicusska
    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
      anubhava over 8 years
      find . -name "$filename.txt" should work with variables in double quotes.
    • ryanpcmcquen
      ryanpcmcquen over 8 years
      @anubhava is correct, you must use double quotes for variables to expand.
    • Sleafar
      Sleafar over 8 years
      What is the value of $F and what is the name of the file you are looking for?
    • nicusska
      nicusska over 8 years
      I 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
    Eric Renouf over 8 years
    you 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
    Alec about 6 years
    You 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.