文件压缩
# 什么是文件压缩
- 将多个文件或目录合并成为一个特殊的文件。
# 为什么要对文件进行压缩
- 当我们在传输大量的文件时,通常都会选择将该文件进行压缩,然后再进行传输
- 首先:压缩后的文件会比压缩前的文件小;
- 其次:多个文件传输很慢,但单个文件传输会很快,同时还能节省网络的消耗;
- (比如:搬家时,单个李往外拿和打包后往外拿? )
# Linux下常见压缩包类型格式
格式 | 压缩工具 |
---|---|
.zip | zip压缩工具 |
.gz | gzip压缩工具,只能压缩文件,会删除原文件(通常配合tar使用) |
.bz2 | bzip2压缩工具,只能压缩文件,会删除原文件(通常配合tar使用) |
.tar.gz | 先使用tar命令归档打包,然后使用gzip压缩 |
.tar.bz2 | 先使用tar命令归档打包,然后使用bzip压缩 |
# 文件打包与压缩-gzip
使用gzip
方式进行压缩文件
[root@web ~]# yum install gzip -y
[root@web ~]# gzip file # 对文件进行压缩
[root@web ~]# zcat file.gz # 查看gz压缩后的文件
[root@web ~]# gzip -d file.gz # 解压gzip的压缩包
# 使用场景:当需要让某个文件不生效时
[root@web ~]# gzip centos-Vault.repo # --> Centos-Vault.repo.gz
[root@web ~]# zcat CentOS-vault.repo.gz # --> 查看不想解压的压缩包文件内容
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 文件打包与压缩-zip
使用zip
命令可以对文件进行压缩打包,解压则需要使用unzip
命令
# 默认情况下没有zip和unzip工具,需要进行安装
[root@web ~]# yum install zip unzip -y
# 压缩文件为zip包
[root@web ~]# zip filename.zip filename
# 压缩目录为zip包
[root@web ~]# zip -r dir.zip dir/
# 查看zip压缩包是否是完整的
[root@web ~]# zip -T filename.zip
test of filename.zip oK
# 不解压压缩包查看压缩包中的内容
[root@web ~]# unzip -l filename.zip
[root@web ~]# unzip -t filename.zip
# 解压zip文件包,默认解压至当前目录
[root@web ~]# unzip filename.zip
# 解压zip内容至/opt目录
[root@web ~]# unzip filename.zip -d /opt/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 文件打包与压缩-tar
tar
是linux
下最常用的压缩与解压缩,支持文件和目录的压缩归档
# 语法:tar [-zjxcvfpP] filename
c # 创建新的归档文件
x # 对归档文件解包
t # 列出归档文件里的文件列表
v # 输出命令的归档或解包的过程
f # 指定包文件名,多参数f写最后
z # 使用gzip压缩归档后的文件(.tar.gz)
j # 使用bzip2压缩归档后的文件(.tar.bz2)
J # 使用xz压缩归档后的文件(tar.xz)
C # 指定解压目录位置
X # 排除多个文件(写入需要排除的文件名称)
h # 打包软链接
--hard-dereference # 打包硬链接
--exclude # 在打包的时候写入需要排除文件或目录
# 常用打包与压缩组合
czf # 打包tar.gz格式
cjf # 打包tar.bz格式
cJf # 打包tar.xz格式
zxf # 解压tar.gz格式
jxf # 解压tar.bz格式
xf # 自动选择解压模式
tf # 查看压缩包内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
将文件或目录进行打包压缩
# 以gzip归档方式打包并压缩 [root@web ~]# tar czf test.tar.gz test/ test2/ # 以bz2方式压缩 [root@web ~]# tar cjf test.tar.bz2 dir.txt dir/ # 打包链接文件,打包链接文件的真实文件 [root@web ~]# tar czfh local.tar.gz /etc/rc.local # 打包/tmp下所有文件 [root@web ~]# find /tmp/ -type f | xargs tar czf tmp.tar.gz # 打包/tmp下所有文件 [root@web ~]# tar czf tmp.tar.gz $(find /tmp/ -type f)
1
2
3
4
5
6
7
8
9
10
11
12
13
14排除文件,并打包压缩
# 排除单个文件 [root@web ~]# tar czf etc.tar.gz --exclude=/etc/services /etc/ # 排除多个文件 [root@web ~]# tar czf etc.tar.gz --exclude=/etc/services --exclude=/etc/rc.local /etc/ # 将需要排除的文件写入文件中 [root@web ~]# cat paichu.list /etc/services /etc/rc.local /etc/rc.d/rc.local # 指定需要排除的文件列表,最后进行打包压缩 [root@web ~]# tar czfX etc.tar.gz paichu.list /etc/
1
2
3
4
5
6
7
8
9
10
11
12
13查看压缩文件
# 查看压缩包内容和解压 [root@web ~]# tar tf test.tar.gz
1
2解压缩文件
# 解压至当前目录 [root@web ~]# tar xf test.tar.gz # 将解压内容存储至指定的/tmp目录 [root@web ~]# tar xf /etc/local.tar.gz -C /tmp
1
2
3
4
5
Last Updated: 2021/11/12, 16:51:33