I am having millions of files without extension and I want to sort them into various folders. I am able to identify the files by "file" but then I end with lot of different types which I can process manually. I would like to use output of "file" to grep i.e. "Word" and then move it into the "office" folder. I am able to write it for a single filetype, but not for all the filetypes I have. I am missing the conditions if then. I am using cygwin. Anyone could help me to give me an idea how to do this? Thank you!


1 Answer 1


Instead of grep, you could use simple pattern matching in a shell case construct. For example:


for f in *; do 

  [ -f "$f" ] || continue

  ftype="$(file -b -- "$f")"

  case $ftype in 
    *"shell script"*)
      echo mv -- "$f" scripts/
    *"C source"*|*"C++ source"*) 
      echo mv -- "$f" src/


    *) printf '%s: skipping unrecognized type "%s"\n' "$f" "$ftype" >&2


The destination directories must exist (although it would be straightforward to conditionally create them, with mkdir -p). Remove the echoes once you are happy that it is doing the right thing.

  • Thank you, this is a nice approach.
    – Petr
    Jul 2, 2020 at 11:36

You must log in to answer this question.

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