Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

file 命令詳解:不靠副檔名判斷檔案類型與編碼

命令簡介

file 用來辨識檔案類型,也能判別部分檔案的編碼。它的原理是讀取檔案頭部資訊,而非像 Windows 那樣依副檔名猜測,因此更可靠。

執行權限:所有使用者
指令路徑:/usr/bin/file
語法:
file [ -bchikLnNprsvz ] [ -f namefile ] [ -F separator ] [ -m magicfiles ] file ...

常用參數:

file 命令詳解:不靠副檔名判斷檔案類型與編碼

1. 查看說明

[root@DB-Server ~]# file --help
Usage: file [OPTION]... [FILE]...
 -m, --magic-file LIST 以冒號分隔的 magic 檔清單
 -z, --uncompress    嘗試檢視壓縮檔內部
 -b, --brief         不輸出檔名
 -c, --checking-printout 印出 magic 檔解析結果,供除錯
 -f, --files-from FILE 從檔案讀取待檢查清單
 -F, --separator string 自訂分隔字串
 -i, --mime          輸出 mime 類型
 -k, --keep-going    不但在第一個符合處停止
 -L, --dereference   追隨符號連結
 -s, --special-files 特殊裝置檔視為一般檔案

更詳細的內容可用 man file 查閱。

2. 只顯示格式與編碼(-b)

[root@DB-Server ~]# file Temp.txt
Temp.txt: UTF-8 Unicode text, with very long lines, with CRLF line terminators

[root@DB-Server ~]# file -b Temp.txt
UTF-8 Unicode text, with very long lines, with CRLF line terminators

file 命令詳解:不靠副檔名判斷檔案類型與編碼

3. 輸出 mime 字串(-i)

[root@DB-Server ~]# file -i Temp.txt
Temp.txt: text/plain; charset=utf-8

4. 從清單檔批次判別(-f)

這個參數很適合 shell 腳本批次分類檔案。也可以直接對多個檔案下指令:

tecmint@tecmint ~/Linux-Tricks $ file BACKUP/
BACKUP/: directory

tecmint@tecmint ~/Linux-Tricks $ file master.zip
master.zip: Zip archive data, at least v1.0 to extract

tecmint@tecmint ~/Linux-Tricks $ file crossroads-stable.tar.gz
crossroads-stable.tar.gz: gzip compressed data, from Unix

tecmint@tecmint ~/Linux-Tricks $ file Linux-Security-Optimization-Book.gif
Linux-Security-Optimization-Book.gif: GIF image data, version 89a, 200 x 259

tecmint@tecmint ~/Linux-Tricks $ file EDWARD-MAYA-2011-2012-NEW-REMIX.mp3
...: Audio file with ID3 version 2.3.0, MPEG ADTS, layer III, 192 kbps, 44.1 kHz

tecmint@tecmint ~/Linux-Tricks $ file /dev/sda1
/dev/sda1: block special

tecmint@tecmint ~/Linux-Tricks $ file /dev/tty1
/dev/tty1: character special

5. 檢視壓縮檔內容(-z)

[root@DB-Server ~]# file -z Temp.txt.gz
Temp.txt.gz: UTF-8 Unicode text ... (gzip compressed data, was "Temp.txt", from Unix)

6. 檢視軟連結目標(-L)

[root@DB-Server ~]# ln -s Temp.txt.gz sfile
[root@DB-Server ~]# file sfile
sfile: symbolic link to `Temp.txt.gz'

[root@DB-Server ~]# file -L sfile
sfile: gzip compressed data, was "Temp.txt", from Unix

搭配使用建議

實務上最實用的是 -b 與 -i:前者讓輸出乾淨、易於 parse,後者直接給出 charset,處理大量文字檔匯入時特別有用。若檔案被誤植副檔名(例如把 tar.gz 命名成 .zip),file 也能立刻揭穿真相,比事後開檔失敗再回頭找原因省事得多。

Copyright © Linux教程網 All Rights Reserved