linux 高效压缩工具之xz的压缩解压使用

xz是什么

高压缩率的工具,它使用 LZMA2 压缩算法,生成的压缩文件比传统使用的 gzip、bzip2 生成的压缩文件更小,
不过xz也有一个坏处就是压缩时间比较长,比7z压缩时间还长一些。不过压缩主要用于归档,不介意的可以忽略。
擅长压缩文本和日志文件,针对这块的压缩率,是目前我发现效率最高的,没有之一。

语法结构:

xz [选项] [参数]

主要参数说明:

  • -z --compress # 强制压缩
  • -d --decompress # 解压缩
  • -t --test # 测试压缩文件的完整性
  • -k --keep # 压缩或解压时保持源文件不被删除
  • -l --list # 列出有关.xz文件的信息
  • -0~9 # 指定压缩率,默认为6;
  • -h --help # 显示这个简洁的帮助并退出
  • -H --long-help # 显示更多帮助(还列出了高级选项)
  • -V --version # 显示版本号并退出

有些操作系统可以没有自带,需要执行yum install xz自行安装一下。
记得先装epel源yum install epel-release

压缩和解压案例

压缩使用

首先使用dd生成一个大文件,再使用xz压缩看效果

[root@VM-0-13-centos ~]# dd if=/dev/zero of=test.jpg bs=1M count=1024
1024+0 records in
1024+0 records out
1073741824 bytes (1.1 GB, 1.0 GiB) copied, 0.588149 s, 1.8 GB/s
[root@VM-0-13-centos ~]# xz test.jpg
[root@VM-0-13-centos ~]# ll -h
total 596K
-rw-r--r-- 1 root root 153K Jan 29 18:11 test.jpg.xz

可以看到已经对test.jpg文件进行压缩,格式如上。

解压使用

解压test.jpg.xz使用-d参数,如果保留源文件可以加-k

[root@VM-0-13-centos ~]# xz -dk test.jpg.xz 
[root@VM-0-13-centos ~]# ll -h test*
-rw-r--r-- 1 root root 1.0G Jan 29 18:11 test.jpg
-rw-r--r-- 1 root root 153K Jan 29 18:11 test.jpg.xz

可以看到压缩文件被保留了。

额外用法

使用参数 -l 显示 .xz 文件的基本信息。基本信息包括压缩率、数据完整性验证方式等。

[root@VM-0-13-centos ~]# xz -l test.jpg.xz 
Strms Blocks Compressed Uncompressed Ratio Check Filename
 1 1 152.7 KiB 1,024.0 MiB 0.000 CRC64 test.jpg.xz

使用xzcat对已压缩日志直接查看,再grep过滤关键信息,或xzgrep直接过滤也行,省去再解压步骤。

[root@VM-0-13-centos ~]# xz -k /root/wechatbot/bin/nohup.out
[root@VM-0-13-centos ~]# cd /root/wechatbot/bin/
[root@VM-0-13-centos bin]# ll
total 38456
-rw-r--r-- 1 root root 92 Dec 10 12:06 config.json
-rw------- 1 root root 674304 Jan 29 18:33 nohup.out
-rw------- 1 root root 83000 Jan 29 18:32 nohup.out.xz
[root@VM-0-13-centos bin]# xzcat nohup.out.xz |grep "18:29"
2023/01/27 18:29:02 RetCode:0 Selector:0
2023/01/27 18:29:27 RetCode:0 Selector:0
2023/01/27 18:29:52 RetCode:0 Selector:0
2023/01/28 09:18:29 RetCode:0 Selector:0
2023/01/28 18:29:06 RetCode:0 Selector:0
2023/01/28 18:29:31 RetCode:0 Selector:0
2023/01/28 18:29:56 RetCode:0 Selector:0

---- 钢铁侠的知识库 2023.01.29

总结

以上就是xz压缩解压常见用法,工作中一般会写脚本对日志进行定时压缩,
有需要查看关键报错内容的时候使用xzgrep即可,无需再解压,非常方便。

想了解更多xz --helpxz -H,或官网:https://tukaani.org/xz/

作者:钢铁侠的知识库原文地址:https://www.cnblogs.com/jiba/p/17073671.html

%s 个评论

要回复文章请先登录注册