Tuesday 10 April 2012

Bash script to sort files into folders by filetype

This script will list the files in the current directory, create (if needed) a folder for each type of file and them move the files into their respective folders:
#!/bin/bash
file -N --mime-type -F"-&-" * | grep -v $0 | awk -F"-&-" 'BEGIN{q="\047"}
{
o=$1
#gsub("/","_",$2); # uncomment to make folders like "image_jpeg" instead of "image/jpeg"
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="mv "q f q" "q files[f]"/"f q
print cmd
#system(cmd) #uncomment to use
}
}'

Possibly Related Posts

No comments:

Post a Comment