【Linux】文件的压缩和解压——gzip、bzip2、tar

时间:2023-01-29 20:00:10

文件压缩和解压——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