如何知道 zip 或 tar.gz 檔案中檔案的真實檔案類型?

如何知道 zip 或 tar.gz 檔案中檔案的真實檔案類型?

我有多個 .tar.gz 和 .zip 文件,我想知道這些文件中文件的文件類型而不解壓它們。我怎樣才能做到這一點。我可以使用命令tar -tzf 'filename'和列出 .tar.gz 檔案unzip -l 'filename'。我找不到識別這些文件中的文件類型的方法。我怎樣才能實現這個目標?我使用的是centos 6.6

命令輸出tar -tzf 'test.tar.gz'

-rw-r--r-- root/root     89403 2019-05-26 11:31 abc.tar.gz
-rw------- root/root      2842 2019-05-26 09:41 anaconda-ks.cfg
-rw-r--r-- root/root      8823 2019-05-26 09:41 install.log
-rw-r--r-- root/root      3314 2019-05-26 09:40 install.log.syslog
-rw-r--r-- root/root    122880 2019-05-26 11:28 tin.tar
-rw-r--r-- root/root     25543 2019-05-26 11:20 tito.zip
-rw-r--r-- root/root     25487 2019-05-27 07:48 tito.ZIP

的輸出unzip -l test.zip

 Length      Date    Time    Name
---------  ---------- -----   ----
    89403  05-26-2019 11:31   abc.tar.gz
     2842  05-26-2019 09:41   anaconda-ks.cfg
     8823  05-26-2019 09:41   install.log
     3314  05-26-2019 09:40   install.log.syslog
   122880  05-26-2019 11:28   tin.tar
    25543  05-26-2019 11:20   tito.zip
    25487  05-27-2019 07:48   tito.ZIP
---------                     -------
   278292                     7 files

答案1

使用 GNU tar

tar --to-command='exec file -b -' -xvvf file.tar.gz

對於文件,您可以使用以下命令即時zip轉換並再次使用 GNU來呼叫每個成員:tarbsdtartarfile

bsdtar cf - @file.zip | tar --to-command='exec file -b -' -xvvf -

它給出如下輸出:

-rw-rw-r-- 0/0            7653 1999-12-30 10:26 WINOBJ.HLP
MS Windows 3.1 help, Thu Dec 30 15:26:17 1999, 7653 bytes
-rw-rw-r-- 0/0            7005 2006-07-28 08:32 Eula.txt
Non-ISO extended-ASCII text, with very long lines, with CRLF line terminators
-rw-rw-r-- 0/0          729464 2011-02-14 11:37 Winobj.exe
PE32 executable (GUI) Intel 80386, for MS Windows

file指令猜測類型使用基於文件前幾個位元組的啟發式方法來分析文件。因此,無論如何,都需要從文件中提取資料。即使要報告tar tvf輸出,也tar需要讀取並解壓縮完整的存檔,因為資訊儲存在每個存檔成員的內容之前,但上述解決方案都沒有提取成員到磁碟,資料透過管道來回傳遞,bsdtar歸檔tar成員的內容甚至沒有作為一個整體儲存在記憶體中。tarfile

file讀取檔案的前幾個字節後返回後,GNUtar會巧妙地處理它,並在為下一個存檔成員運行下一個命令之前跳過存檔成員的其餘部分(而不是死於 SIGPIPE)file

從效率的角度來看,它不是最佳的,因為它為每個常規文件歸檔成員運行一個命令sh(解釋exec file -b -命令列)和一個命令。file我們使用exec相同的過程來重複使用shfile(對於那些sh像這樣的實作dash本身不會進行最佳化)。

答案2

file命令應該告訴您有關文件本身的資訊:

$ file test.zip
test.zip: Zip archive data, at least v1.0 to extract
$ file test.tar.gz
test.tar.gz: gzip compressed data, last modified: Sun May 26 11:28:34 2019, from Uniz

但對於檔案中的文件,您需要提取它們並file單獨運行每個文件。

相關內容