HNoob HNoob - 1 month ago 5x
Linux Question

Sort files according to their filetype

After an HD problem and some work, I have a bunch of files with names like "f1234", "f1235", etc.

My goal is to sort this files according to their filetype. For example, I want to move all the PDF files in the "pdfs" directory.

For one file, I can do : "file f1234", and if it's a PDF, I can "mv f1234 pdfs/". But I have thousands of file... Can you help me with a bash or zsh command for sort all the PDF in one pass ? Thanks


The hard part here is reliably turning the output of file into a directory name. I think probably the best candidate for that is the mime-type of the file rather than the human readable output of file. I'd use something like:

mkdir sorted
for f in f*
  d=$(file -b --mime-type "$f" | tr / -)
  mkdir -p "sorted/$d"
  mv "$f" "sorted/$d/"

Obviously I'd test that out a bit before running it on your files, but something pretty close to that should work.