How to Determine File Type & Encoding from Command Line in Mac OS X
Typically if you’re looking to determine the file type and encoding of an item, you can simply look at the file in the Mac Finder, check the file name extension, Get Info about the file, or even open it to quickly find out what the file is. Of course, that’s limited to the user friendly file system of OS X, and there are occasions where it may be necessary to detect how a file is encoded or what a file type is from the command line, often with less obvious clues (or no clues at all) than a visible file extension.
If you’re in a situation where you need to figure out what a particular file is and how it’s encoded, you can use the ‘file’ command with the uppercase i flag to quickly see what the file is, and it’s character set. To try this yourself, launch the Terminal application and issue the proper syntax.
The syntax to determine file encoding type and file type in Mac OS X (and from the linux command line as well) looks like the following:
file -I filename
Do note the flag is a capital ‘i’ and not a lowercase l. The output of the properly executed command will read like the following:
/Path/To/Filename: fileformat/filetype; charset=encoding
Let’s look at a few examples, first is checking a file which turns out to be an image:
file -I ~/Desktop/iphone-plus
/Users/Paul/Desktop/iphone-plus: image/jpeg; charset=binary
The file type is clearly shown as is the character set.
Again, with another file, which shows as an xml encoded as us-ascii:
file -I osxdaily.com.webloc
osxdaily.com.webloc: application/xml; charset=us-ascii
Another example which turns out to be a plain old text file:
file -I ~/Documents/diywatch
~/Documents/diywatch: text/plain; charset=us-ascii
And another example which turns out to be an executable binary application:
file -I /usr/sbin/streamy
/usr/sbin/streamy: application/octet-stream; charset=binary
This command line approach to determining file type and encoding can be helpful for many reasons, whether for usage in a script, for remote troubleshooting or maintenance with ssh, finding specific file types and file formats with the built-in search functions in OS X, or even for your own purposes of determining what a mystery file is, what app to open it with, and perhaps what extension type it should have if it’s missing one.