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 problem I need a way to automatically add the file extension, which facilitates the process of reorganizing 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`
    extension=`getExtension $file`
    rename -nv 's/(.*)/$1\.'$extension'/' $file

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)

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: