如何将顶部快照流式传输到文件中?

如何将顶部快照流式传输到文件中?

top有没有办法将给定时刻的快照保存到文件中?

我试过

top > top.out

但内容与 STDOUT 中的 top 完全不同:

^[[H^[[2J^[(B^[[mtop - 16:09:49 up 18 days, 21:46,  4 users,  load average: 2.00, 1.90, 1.87^[(B^[[m^[[39;49m^[[K
Tasks:^[(B^[[m^[[39;49m^[(B^[[m 286 ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m   1 ^[(B^[[m^[[39;49mrunning,^[(B^[[m^[[39;49m^[(B^[[m 285 ^[(B^[[m^[[39;49msleeping,^[(B^[[m^[[39;49m^[(B^[[m   0 ^[(B^[[m^[[39;49mstopped,^[(B^[[m^[[39;49m^[(B^[[m   0 ^[(B^[[m^[[39;49mzombie^[(B^[[m^[[39;49m^[[K
Cpu(s):^[(B^[[m^[[39;49m^[(B^[[m  5.9%^[(B^[[m^[[39;49mus,^[(B^[[m^[[39;49m^[(B^[[m  0.1%^[(B^[[m^[[39;49msy,^[(B^[[m^[[39;49m^[(B^[[m  0.0%^[(B^[[m^[[39;49mni,^[(B^[[m^[[39;49m^[(B^[[m 93.5%^[(B^[[m^[[39;49mid,^[(B^[[m^[[39;49m^[(B^[[m  0.3%^[(B^[[m^[[39;49mwa,^[(B^[[m^[[39;49m^[(B^[[m  0.0%^[(B^[[m^[[39;49mhi,^[(B^[[m^[[39;49m^[(B^[[m  0.1%^[(B^[[m^[[39;49msi,^[(B^[[m^[[39;49m^[(B^[[m  0.0%^[(B^[[m^[[39;49mst^[(B^[[m^[[39;49m^[[K
Mem: ^[(B^[[m^[[39;49m^[(B^[[m 64322524k ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m 46529492k ^[(B^[[m^[[39;49mused,^[(B^[[m^[[39;49m^[(B^[[m 17793032k ^[(B^[[m^[[39;49mfree,^[(B^[[m^[[39;49m^[(B^[[m   141304k ^[(B^[[m^[[39;49mbuffers^[(B^[[m^[[39;49m^[[K
Swap:^[(B^[[m^[[39;49m^[(B^[[m  6289436k ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m      696k ^[(B^[[m^[[39;49mused,^[(B^[[m^[[39;49m^[(B^[[m  6288740k ^[(B^[[m^[[39;49mfree,^[(B^[[m^[[39;49m^[(B^[[m 15289220k ^[(B^[[m^[[39;49mcached^[(B^[[m^[[39;49m^[[K
^[[6;1H

答案1

问题是top默认情况下包含 ANSI/VT100 转义码。在这种情况下,似乎您想要的只是“原始”文本输出(即不是某些文本应加粗等的信息)。幸运的是,top内置了对此操作模式的支持,在其文档中称为“批处理模式”。

从顶部手册页 ( man top):

-n : Number of iterations limit as:  -n number
     Specifies the maximum number of iterations, or frames, top should
     produce before ending.
-b : Batch mode operation
     Starts  top in 'Batch mode', which could be useful for sending output
     from top to other programs or to a file. In this mode, top will not
     accept input and runs until the iterations limit you've set with
     the '-n' command-line option or until killed.

所以...

top -n 1 -b > top.out

对于其他没有像 top 这样方便的“-b”类型开关的命令行实用程序,也可以使用抗过滤器。下载、编译、安装。那么你可以...

top -n 1 | ansifilter > top.out

相关内容