1.什么是文件压缩
将多个文件或目录合并成一个特殊的文件;
2.为什么要对文件进行压缩
当我们在传输大量的文件时,通常都会选择将该文件压缩,再进行传输;这样可以减小文件的体积,加快资源的传输,节省网络的带宽;
3.Windows的压缩包与Linux的压缩包能否互通
Windows:rar zip
Linux:zip tar.gz
Windows和Linux互通建议选择zip
4.Linux下压缩包有哪些常见的类型
| 格式 | 压缩工具 |
|---|---|
| .zip | zip压缩工具 |
| .gz | gzip压缩工具,只能压缩文件,会删除源文件(通常配合tar使用) |
| .bz2 | bzip2压缩工具,只能压缩文件,会删除源文件(通常配合tar使用) |
| .tar.gz | 先使用tar命令归档打包,然后使用gzip压缩 |
| .tar.bz2 | 先使用tar命令归档打包,然后使用bzip压缩 |
5.打包与压缩
(1)gzip打包与压缩
仅对文件有效
[root@peachcat1 ~]# yum install gzip -y #下载
[root@peachcat1 ~]# gzip file#对文件进行压缩
[root@peachcat1 ~]# zcat file.gz #查看gz压缩后的文件
[root@peachcat1 ~]# gzip -d file.gz #解压gzip的压缩包
#使用场景:当需要让某个文件不生效时
(2)zip打包与压缩
#安装
[root@peachcat1 ~]# yum install zip unzip -y
#对文件进行压缩
[root@peachcat1 ~]# zip file.zip file
#对目录进行压缩
[root@peachcat1 ~]# zip -r opt.zip opt/
#查看压缩包是否完整
[root@peachcat1 ~]# zip -T file.zip
test of file.zip OK
#不解压压缩查看压缩包中的内容
[root@peachcat1 ~]# unzip -l file.zip
Archive: file.zip
Length Date Time Name
--------- ---------- ----- ----
14 08-13-2019 14:46 file
--------- -------
14 1 file
#查看压缩文件是否正确
[root@peachcat1 ~]# unzip -t file.zip
Archive: file.zip
testing: file OK
No errors detected in compressed data of file.zip.
#解压文件,默认解压到当前目录
[root@peachcat1 ~]# unzip file.zip
#解压文件到/opt/目录下
[root@peachcat1 ~]# unzip file.zip -d /opt/
Archive: file.zip
extracting: /opt/file
(3)tar打包与压缩
tar是Linux下最常用的压缩与解压缩,支持文件和目录的压缩归档
c:创建新的归档文件
x:对归档文件解包
t:列出归档文件里的文件列表
v:输出命令的归档或解包的过程
f:指定包文件名,多参数f写最后
z:使用gzip压缩归档后的文件(.tar .gz)
j:使用bzip压缩归档后的文件(.tar .bz2)
J:使用xz压缩归档后的文件
C:指定解压目录位置
X:排除多个文件(写入需要排除的文件名称)
h:打包软链接
--exclude:在打包的时候写入需要排除文件或目录
#常用打包与压缩组合
czf:打包tar.gz格式
cjf:打包tar.bz格式
cJf:打包tar.xz格式
zxf:解压tar.gz格式
jxf:解压tar.bz格式
xf:自动选择解压模式
tf:查看压缩包内容
①将文件或目录进行打包压缩
#以gzip归档方式打包并压缩
[root@peachcat1 ~]# tar czf a.tar.gz abc/ abcd/
#以bz2方式压缩
[root@peachcat1 ~]# tar cjf a.tar.bz2 abc/ abcd/
#打包链接文件,打包链接文件的真实文件
[root@peachcat1 /]# tar czfh local.tar.gz etc/rc.local
#打包/tmp下所有文件
[root@peachcat1 /]# find tmp/ -type f | xargs tar czf tmp.tar.gz
[root@peachcat1 /]# tar czf tmp.tar.gz $(find tmp/ -type f)
②排除文件,并打包压缩
#排除单个文件
[root@peachcat1 /]# tar czf etc.tar.gz --exclude=etc/services etc/
#排除多个文件
[root@peachcat1 /]# tar czf etc.tar.gz --exclude=etc/services etc/ --exclude=etc/rc.local etc/
#将需要排除的文件写入文件中
[root@peachcat1 /]# cat paichu.list
etc/services
etc/rc.local
[root@peachcat1 /]# tar czfX etc.tar.gz paichu.list etc/
③查看压缩文件
#查看压缩包内容和解压
[root@peachcat1 /]# tar tf tmp.tar.gz
④解压缩文件
#解压至当前目录
[root@peachcat1 /]# tar xf tmp.tar.gz
#解压至指定目录
[root@peachcat1 /]# tar xf tmp.tar.gz -C /tmp