1. 程式人生 > >【Linux】檔案的壓縮和解壓——gzip、bzip2、tar

【Linux】檔案的壓縮和解壓——gzip、bzip2、tar

檔案壓縮和解壓——gzip

現在test目錄下有一個檔案test_txt和一個目錄tar-test,tar-test目錄下也有一個檔案,使用gzip對檔案test_txt進行壓縮和解壓。

[lx@localhost test]$ ls 
    tar-test  test_txt
[lx@localhost test]$ ls ./tar-test/
    test_txt
[lx@localhost test]$ gzip test_txt 
[lx@localhost test]$ ls
    tar-test  test_txt.gz
[lx@localhost test]$ gzip tar-test/
    gzip: tar-test/ is a directory -- ignored   //gzip只能對檔案進行壓縮
[lx@localhost test]$ gzip -d test_txt.gz [lx@localhost test]$ ls tar-test test_txt

另一種壓縮比更高的壓縮命令——bzip2

和gzip操作幾乎一樣,只是壓縮方式不同,注意字尾。

[lx@localhost test]$ ls
   tar-test  test_txt
[lx@localhost test]$ bzip2 test_txt 
[lx@localhost test]$ ls 
   tar-test  test_txt.bz2
[lx@localhost test]$ 
bzip2 -d test_txt.bz2 [lx@localhost test]$ ls tar-test test_txt

以上兩種壓縮命令都能對單個檔案操作,tar則可以將檔案打包,也可以加入壓縮功能。

打包壓縮和解壓——tar

格式:

對於壓縮:tar [引數] 目標目標檔名 要壓縮的目錄
對於解壓:tar [引數] 要解壓的檔名 要解壓到哪

引數:

-c:打包檔案
-x:解開包
–delete:從包中刪除檔案
-r:追加檔案到包中
-t:列出打包檔案的內容

-C:指定解壓、壓縮路徑
-f:指定打包後的檔名
-j:使用bzip2格式壓縮或解壓
-z:使用gzip格式壓縮或解壓
–remove-file:打包後刪除原始檔

例子:
將./tar-test/目錄打包並以gzip格式壓縮,命名為tar-test.tar.gz,命名可以隨意,但是加上字尾可以讓人一目瞭然

[lx@localhost test]$ tar -czf  tar-test.tar.gz ./tar-test/
[lx@localhost test]$ ls 
    tar-test.tar.gz  tar-test  test_txt

將tar-test.tar.gz解壓到./tar-test/目錄:

lx@localhost test]$ tar -xzf tar-test.tar.gz -C ./tar-test/
[lx@localhost test]$ ls ./tar-test
    tar-test  test_txt