Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable in find command?

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;
like image 994
nicusska Avatar asked Aug 21 '15 14:08

nicusska


1 Answers

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.

like image 73
ryanpcmcquen Avatar answered Oct 06 '22 18:10

ryanpcmcquen