How to chain 'mimetype -b' and 'find' command to get file names and file type in same csv?

Viewed 171

I would like to get filenames, creation dates, modification dates and file mime-types from directory structure. I've made a script which reads as follows :

#!/bin/bash
output="file_list.csv"

## columns
echo '"File name";"Creation date";"Modification date";"Mime type"' > $output

## content
find $1 -type f -printf '"%f";"%Tc";"%Cc";"no idea!"\n' >> $output

which gives me encouraging results :

"File name";"Creation date";"Modification date";"Mime type"
"Exercice 4 Cluster.xlsx";"ven. 27 mars 2020 10:35:46 CET";"mar. 17 mars 2020 19:14:18 CET";"no idea!"
"Exercice 5 Bayes.xlsx";"ven. 27 mars 2020 10:36:30 CET";"ven. 20 mars 2020 16:18:54 CET";"no idea!"
"Exercice 3 Régression.xlsx";"ven. 27 mars 2020 10:36:46 CET";"mer. 28 août 2019 17:21:10 CEST";"no idea!"
"Archers et Clustering.xlsx";"ven. 27 mars 2020 10:37:34 CET";"lun. 16 mars 2020 14:12:05 CET";"no idea!"
...

but I'm missing a capital thing : how do I get the files mime-types ? It would be great if I could chain the command 'mimetype -b' on each file found with 'find' command, and write it in the convenient column.

Thanks in advance,

Cyril

2 Answers

You might try using the -exec option of the find command, in which the brackets {} represent the name of the current file.

Then, you could remove the new line when appending to an existing file: AFAIK default behavior automatically appends new content to a new line, so the \n should not be necessary.

Last, you want to have a closing quote after your mimetype, so you should not only use the -b option, but the --output-format one, which will give you more control over what you want to display. Hence the third command of your script should look like this:

find $1 -type f -printf '"%f";"%Tc";"%Cc";"' -exec mimetype --output-format %m\" {} \; >> $output

This is what I came up with:

for entry in *; do stat --printf='"%n";"%z";"%y";"' $entry; file -00 --mime-type $entry | cut -d $'\0' -f2; echo '"'; done

Uses a shell "for loop", to perform a stat on the directory entries in the current directory. Then uses file to get the mime type, and pipes that to cut to get only the mime type (by excluding the file name which is also printed by file).

The format for stat is what I believe was requested -- the file name, the last change date, the last modification date (both in ISO format, but could easily be made to UNIX seconds-since-epoch by upper-casing Z and Y).

Availability:

  • file: probably its own package if you are on Linux? But should be preinstalled on macOS I'm guessing.
  • bash/zsh: easily accessible both on Linux and macOS.
  • stat and cut: part of coreutils so should be preinstalled on most systems.
Related