Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a folder (the iPhone Backup) with various files without a suffix.

I want to run a batch process over these files, which detects each file's file-type (with the help of the magic-file database (/usr/share/misc/magic or man file), and automatically changes / renames its file-suffix (from a database file/mime-type<->suffix) accordingly.

Hours of Googling and StackExchange-Searching brought no results, due to the general nature of the involved keywords "file", "magic", "rename", etc. Help appreciated!

share|improve this question
Btw, my original problem was solved, as there is a software, which reorganises that bunch of flat UID-named suffix-less files into a proper folder structure with proper filenames with suffixes. iPhone Backup Extractor (supercrazyawesome.com). Nevertheless it would be good to know how to automatically add file suffixes according to detected filetype of files without a file-suffix in their file-name. – porg Jul 20 '12 at 11:09

What does your type<-> suffix DB look like? It's not that trivial to interpret file's output. I'll just assume: * that the first word file prints is sufficient * this word is the key in a file where each line contains : and value is the suffix we want

For bash I'd write a function that takes as an argument the file type and echoes the suffix:


typetosuffix () {
    grep -E "^\s*$1:" ${MISTERIOUSFILEMIMETYPETOSUFFIXDB}| cut -d : -f 2

With that function you can

for f in $(find /path/to/iphone/backup -type -f)
    FILEWITHOUTSUFFIX = basename $f
    [ ${FILEWITHOUTSUFFIX} = ${FILEWITHOUTSUFFIX%.*} ] && continue #the file has a suffix after all
    TYPE=$(file $f | cut -f 2) #put type determining magic here
    SUFFIXITSSUPPOSEDTOHAVE=$(typetosuffix $TYPE) #fetch suffix from DB
    mv $f $f$SUFFIXITSSUPPOSEDTOHAVE #rename the file
share|improve this answer
I had hoped that the magic DB itself contains such a mapping of mime/file-types to file suffixes, and that there's a ready-made solution for this. Still, thanks a lot for your approach. – porg Jul 20 '12 at 10:59

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.