0

I have a file with name client.txt which contains the company names as below

google
amazon
facebook
apple

With these company names, I have folders and files. I want to know the path of all folders/files and the output should store in a file. eg:

ls -R | grep google\|amazon

If I use this command I will get the google and amazon file/directories path. Similarly, I need for all client name available in that file that too in shell scripting.

2 Answers 2

0

Using scripting to construct a find command, one could do something like (Read man find;man bash):

# Goal: find $dir -name 'google -o -name 'amazon' -o -name 'facebook' ... -print
#
dir="starting directory"
#
names=""
for name in $(cat client.txt) ; do
    if [[ -z "$names" ]] ; then
        names="-name '$name' "
    else
        names="$names -o -name '$name' "
    fi
done
# use 'eval' to expand the 'names' variable at the right time
eval find $dir $names -print
0

A couple of quick'n'dirty ways - based on your grep approach:

find . -print0 | grep -Fzf client.txt

or

shopt -s globstar
printf '%s\0' **/* | grep -Fzf client.txt

Both will be safe for any legal filenames, and give a null-delimited list of paths that you can pass to another program. Note that both will match entries from client.txt anywhere in the path - which may not be what you want.

A more sophisticated way, assembling a list of -name arguments for find using a shell array:

while IFS= read -r client; do namearr+=(-name "$client" -o); done < client.txt

find . \( "${namearr[@]}" -false \) -print

Change -print to -print0 to get null-delimited results like the other methods. Note that this matches exact filenames. You could change -name "$client" to -name "*$client*" to get wildcard matching within the filename (or to -path "*$client*" to get matching anywhere in the path, similar to the grep-based solutions).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .