1. 程式人生 > 其它 >linux基礎之檔案壓縮和打包

linux基礎之檔案壓縮和打包

##1.檔案打包與壓縮概述

####1.1什麼是檔案壓縮

將多個檔案或者目錄合併稱為一個特殊的檔案【壓縮包】

####1.2為什麼需要檔案壓縮

當我們在傳輸大量的檔案時,通常都會選擇將改檔案進行壓縮,然後在進行傳輸

首先;壓縮後的檔案迴避壓縮前的檔案小。一個28G的檔案壓縮後能達到6G

其次:多個檔案傳輸很慢,蛋蛋哥檔案傳輸會很快,同時還能節省網路的消耗

####1.3不同系統的壓縮格式互通

windows的壓縮包與linux的壓縮包能否互通?

windows系統下下,接觸最多的壓縮格式是rar或zip

linux系統上使用的最多的壓縮格式是zip和tar.gz

在linux上的壓縮格式放在windows系統下都是可以正常開啟的

所以一把windows和linux互通通常選擇zip格式

值得注意的是linux不支援windows下的RAR格式的壓縮檔案

windows linux macos 支援zip

tar.gz屬於linux系統特有的一種格式,windows1仍然可以識別並解壓

####1.4linux下常見的壓縮包型別

格式 壓縮工具
.zip zip壓縮工具
.gz gzip壓縮工具,只能壓縮檔案,會刪除原始檔(通常配合tar使用)
.bz2 bzip2壓縮工具,只能壓縮檔案,會刪除原始檔(通常配合tar使用)
.tar.gz 先使用tar命令歸檔打包,然後使用gzip壓縮
.tar.bz2 先使用tar命令歸檔打包,然後使用bzip壓縮

##2檔案打包與壓縮-gzip

gzip僅能打包檔案,並且打包後會刪除原始檔

####2.1gzip壓縮檔案

注意:最小化centos7 需要先安裝

[root@node: ~]#yum install gzip -yfile

[root@node: ~]#gzip file  #對檔案進行壓縮

[root@node: ~]#zcat  file.gz  #檢視gz壓縮後的檔案

[root@node: ~]#gzip -d file.gz  #解壓gzip的壓縮包

#bzip2

[root@node: ~]#yum insatll bzip2 -y

[root@node: ~]#bzip2 file     #對檔案進行壓縮

[root@node: ~]#bzcat file.bz2  #檢視gz壓縮後的檔案

[root@node: ~]#bzip2 -d file.bz2 #解壓gzipd的壓縮包

####2.2gzip應用場景

使用場景:當需要讓某個配置檔案不生效時,且又不想刪除

[root@node: ~]gzip Centos-vault.repo

#--> Centos-vault.repo.gz

[root@node: ~]#zcat CentOS-vault.repo.gz

#--> 檢視不想解壓的壓縮包檔案內容

##3.檔案打包與壓縮-zip

使用zip命令可以對問價進行壓縮打包,解壓則需要使用unzip命令

####3.1zip壓縮檔案

1.預設最小化安裝的作業系統,沒有zip和unzip工具,所以需要安裝

[root@node: ~]#yum install zip unzip -y

2.使用zip壓縮檔案

[root@node: ~]zip filename.zip

[root@node: ~]zip -r dir.zip dir/

####3.2unzip解壓檔案

1.解壓zip檔案包,預設解壓至當前目錄

[root@node: ~]unzip filename.zip

2.解壓zip包內容至/opt目錄

[root@node: ~]unzip filename.zip -d /opt/

3.不解壓壓縮包,檢視壓縮包中的內容

[root@node: ~]unzip -l filename.zip

##4.檔案打包與壓縮-tar

tar命令是linux下最常用的壓縮與解壓縮,支援檔案和目錄的壓縮歸檔

tar語法:tar[-zjxcvfpP]filename

常用打包與壓縮組合命令

####4.1使用tar壓縮檔案

1.將檔案或目錄進行壓縮打包

以gzip歸檔方式打包並壓縮

[root@node: ~]tar czf test.tar.gz test/ test2/

2.打包/tpm下所有檔案

[root@node: ~]find /tmp -type f | xargs tar czf tmp.tar.gz

[root@node: ~]tar czf tmp.tar.gz $(find /tmp -type 
#將前者執行的命令作為引數傳遞後者tar這個命令使用

[root@node: ~]#find ./ -maxdepth 1  -type f ! -name "*.gz" -a ! -name "*.zip" -a ! -name "*.bz2 | xargs tar czf
2.排除檔案並打包壓縮

1.排除單個檔案

[root@node: ~]#tar czf etc.tar.gz --exclude=etc/services etc/


2.排除多個檔案

[root@node: ~]tar czf etc.tar.gz --exclude=etc/services --exclude=etc/rc.local


3.將需要的排除的檔案寫入檔案中

[root@node: ~]#cat paichu.list
etc/servics
etc/rc.local
etc/rc.d/rcc.local


指定需要排除的檔案列表,最後進行打包壓縮

[root@node: ~]#tar czfX etc.tar.gz pai.txt /etc/

使用tar列出檔案

檢視壓縮包內容,但不解壓

[root@node: ~]#tar tf etc.tar.gz

####4.2使用tar解壓檔案

1.預設解壓檔案至當前目錄

解壓至當前目錄
[root@node: ~]tar xf local.tar.gz


指定解壓內容儲存至/opt目錄

[root@node: ~]tar xf /etc/local.tar.gz -C /tmp