压缩和解压文件是Linux下常用的操作,不过也很容易搞错参数,做个笔记~
ZIP文件
使用unzip命令解压zip文件
解压一个zip文件:
1 | unzip test.zip |
指定解压目录:
1 | unzip test.zip -d /path/to/extract |
查看压缩包文件列表:
1 | unzip -l test.zip |
使用zip命令压缩文件
压缩一个文件(夹):
1 | zip -r test.zip /path/to/dir |
注1:选项
-r
表示递归地压缩文件夹中的文件和子文件夹。
注2:这里我经常混淆,错误地把命令写成
zip -r /path/to/dir test.zip
,然后看到报错zip error: Nothing to do!
。因为印象中Linux命令行总是源文件在前,目标文件在后面。比如复制文件:
cp 源文件 目的文件
, 移动文件:mv 源文件 目的文件
,甚至是用unzip解压文件到指定文件夹,都是源文件在前,目标文件在后面。不过可以换一种方式理解,即目的件不存在(需要创建)的时候,要先指定目的文件的名称。
压缩多个文件(夹):
1 | zip -r test.zip dir1 dir2 dir3 |
设置压缩级别(级别1-9,1-速度快,9-文件体积小):
1 | zip -r -9 test.zip /path/to/dir |
设置压缩包解压密码:
1 | zip -r -e test.zip /path/to/dir |
按下回车后输入需要设置的密码。使用unzip解压时,直接使用命令
unzip test.zip
,同样按下回车后输入解压密码。
Tar.gz文件
使用tar命令解压文件
解压一个tar.gz文件到当前文件夹:
1 | tar -xzf test.tar.gz |
-x
选项表示解压
解压到指定目录使用-C
选项:
1 | tar -xzf test.tar.gz -C /path/to/extract |
解压.tar文件:
1 | tar -xf test.tar |
解压.bz2文件:
1 | tar -xjf test.tar.bz2 |
使用tar命令创建.tar.gz压缩包:
1 | tar -czf test.tar.gz /path/to/file |
选项
-c
表示创建压缩包。
使用tar创建.tar压缩包:
1 | tar -cf test.tar /path/to/file |
rar文件
linux默认没有rar和unrar命令,需要安装:
1 | 最新版本查看:https://www.rarlab.com/download.htm |
创建一个rar压缩文件:
1 | rar a test.rar /path/dir/dir |
其中选项
a
表示创建压缩包。
解压rar文件:
1 | unrar e test.rar |
其中选项
-e
表示解压文件。