simone viozzi
simone viozzi

Reputation: 460

How to find and exec based on python variable in google colab

I'm working on google colaboratory and i have to do some elaboration to some files based on their extensions, like:

!find ./ -type f -name "*.djvu" -exec file '{}' ';'

and i expect an output:

./file.djvu: DjVu multiple page document

but when i try to mix bash and python to use a list of exensions:

for f in file_types:
  !echo "*.{f}"
  !find ./ -type f -name "*.{f}" -exec file '{}' ';'
  !echo "*.$f"
  !find ./ -type f -name "*.$f" -exec file '{}' ';'

i get only the output of both the echo but not of the files.

*.djvu
*.djvu
*.jpg
*.jpg
*.pdf
*.pdf

If i remove the exec part it actually find the files so i can't figure out why the find command combined with exec fail in some manner.

If needed i can provide more info/examples.

Upvotes: 1

Views: 1325

Answers (2)

simone viozzi
simone viozzi

Reputation: 460

I found an ugly workaround passing trought a file, so first i write the array to a file in python:

with open('/content/file_types.txt', 'w') as f:
    for ft in file_types:
      f.write(ft + '\n')

and than i read and use it from bash in another cell:

%%bash
filename=/content/protected_file_types.txt

while IFS= read -r f;
do
  find ./ -name "*.$f" -exec file {} ';' ;
done < $filename

Doing so i dont mix bash and python in the same cell as suggested in the comment of another answer.

I hope to find a better solution that maybe use some trick that I'm not aware of.

Upvotes: 1

beepbeep
beepbeep

Reputation: 322

This works for me

declare -a my_array=("pdf" "py")

for i in ${my_array[*]}; do find ./ -type f -name "*.$i" -exec file '{}' ';'; done;

Upvotes: 0

Related Questions