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.
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.
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.
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, .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With