Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort files into folders by filetype on bash (with 'file' command)?

I have thousands of files without extensions after recovery (mostly pictures). I need to sort them into separate folders by filetype (folders must be created during sort process). I can determine filetype in linux using "file" command. Does somebody have bash script for it?

For example: Initial dir contains files: 001, 002, 003, 004. After sorting should be 3 dirs: 'jpeg' contain 001.jpg, 003.jpg; 'tiff' contain 002.tiff and 'others' contain 004.

like image 928
hoxnox Avatar asked Oct 10 '10 20:10

hoxnox


People also ask

How do I sort files in bash?

Bash Sort Files Alphabetically By default, the ls command lists files in ascending order. To reverse the sorting order, pass the -r flag to the ls -l command, like this: ls -lr . Passing the -r flag to the ls -l command applies to other examples in this tutorial.

How do I sort files by type?

To sort files in a different order, click one of the column headings in the file manager. For example, click Type to sort by file type. Click the column heading again to sort in the reverse order. In list view, you can show columns with more attributes and sort on those columns.

How do I sort files in a folder in Linux?

If you add the -X option, ls will sort files by name within each extension category. For example, it will list files without extensions first (in alphanumeric order) followed by files with extensions like . 1, . bz2, .

How do you sort files in shell script?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.


2 Answers

This answer does not execute file command multiple times for each file, which is unnecessary

file  -N --mime-type -F"-&-" * | awk -F"-&-" 'BEGIN{q="\047"}
{
  o=$1
  gsub("/","_",$2);sub("^ +","",$2)
  if (!($2  in dir )) {
    dir[$2]
    cmd="mkdir -p "$2
    print cmd
    #system(cmd) #uncomment to use
  }
  files[o]=$2
}
END{
 for(f in files){
    cmd="cp "q f q"  "q files[f]"/"f".jpg" q
    print cmd
    #system(cmd) #uncomment to use
 }
}'

similarly, can be done with bash4+ script using associative arrays.

like image 62
ghostdog74 Avatar answered Sep 21 '22 23:09

ghostdog74


How about something like this:


mkdir -p `file -b --mime-type *|uniq`
for x in `ls`
do
        cp $x `file -b --mime-type $x`
done

I use cp, it can't work with directories.

like image 43
Adam Trhon Avatar answered Sep 17 '22 23:09

Adam Trhon