nicusska
nicusska

Reputation: 187

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;

Upvotes: 9

Views: 23711

Answers (1)

ryanpcmcquen
ryanpcmcquen

Reputation: 6475

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.

Upvotes: 6

Related Questions