Recover file extensions for multiple files (Linux)

When recovering files I sometimes face the problem of lost file names and file extensions (most recent case here). To help me dealing with this I problem I need a way to automatically add the file extension, which facilitates the process of reorganising the recovered files.

I based my idea on Drav Sloans SO answer and wrote a minimalistic shell script skeleton. It basically just defines a function which uses the mime-types to determine a possible file extension and renames the files using this file extension. Currently the script assumes the following:

  • All files are located in the current folder
  • All files miss the file extension
  • You are fine by using any of the possible file extensions defined in /etc/mime.types.
function getExtension {
    file -i $1  | awk '{FS=" "} {print $2}' | tr -d ";" | xargs -I {} grep -E "^"{}"    " /etc/mime.types  | awk '{print $2}'
}

for file in `find . -type f`
do
    extension=`getExtension $file`
    rename -nv 's/(.*)/$1\.'$extension'/' $file
done

This small script adds missing file-extensions to your files which helps a great deal in restructuring them or finding specific files. Depending on your specific needs you might want to add parameter parsing or further decision logic for mime types with multiple associated file extensions. (in time I might post a tutorial on parameter parsing for bash-scripts)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: