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.
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.
Dadam's answer adjustment:
#!/bin/bash
file --mime-type -F"&" [YOUR PATH]/* > filetypes.txt
mkdir -p `cut -f2 -d"&" filetypes.txt | sed 's/[ ,:]//g' | sort -u`
IFS=$'\n'
for x in `cut -f1 -d"&" filetypes.txt`
do
mv "$x" `file -b --mime-type "$x" | sed 's/[ ,:]//g'`
done
I use this and it works for me :
#!/bin/bash
self_name=`basename "$0"`
for f in *
do
if [ -f "$f" ] && [ "$f" != "$self_name" ]; then
filename="${f%.*}"
ext="${f##*.}"
mkdir $ext
mv "$f" "$ext/$f"
htmlfiles="{$f}_files"
if [ -d "$htmlfiles" ];then
mv "$htmlfiles" "$ext/$htmlfiles"
fi
if [ $? -ne 0 ]
then
echo "Error: Failed mv $f"
fi
fi
if [ -d "$f" ];then
mv "$f" "$ext/$f"
fi
done
You should put it in your directory and run it and it make a sub directory for extension
精彩评论