我必须将top命令的输出保存到变量中,我这样做:
myvar=`top -b -n1 | head -n 18`
问题在于它似乎忽略了返回字符,因此当我回显$myvar
的内容时,我看到类似的内容:
top - 15:15:38 up 745 days, 15:08, 5 users, load average: 0.22, 0.27, 0.32 Tasks: 133 total, 1 running, 132 sleeping, 0 stopped, 0 zombie Cpu(s): 6.4% us, 1.6%sy, 0.0% ni, 91.7% id, 0.3% wa, 0.0% hi, 0.0% si Mem: 2074716k total, 2038716k used, 36000k free, 84668k buffers Swap: 4192924k total, 107268k used, 4085656k etc...
如何正确保存所有热门数据?
答案 0 :(得分:16)
注意区别:
#! /bin/bash
x=`top -b -n 1 | head -n 5`
echo $x
echo --------------------
echo "$x"
输出:
top - 14:33:09 up 7 days, 5:58, 4 users, load average: 0.00, 0.00, 0.09 Tasks: 253 total, 2 running, 251 sleeping, 0 stopped, 0 zombie Cpu(s): 1.6%us, 0.4%sy, 70.3%ni, 27.6%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 3926784k total, 3644624k used, 282160k free, 232696k buffers Swap: 9936160k total, 101156k used, 9835004k free, 1287352k cached -------------------- top - 14:33:09 up 7 days, 5:58, 4 users, load average: 0.00, 0.00, 0.09 Tasks: 253 total, 2 running, 251 sleeping, 0 stopped, 0 zombie Cpu(s): 1.6%us, 0.4%sy, 70.3%ni, 27.6%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 3926784k total, 3644624k used, 282160k free, 232696k buffers Swap: 9936160k total, 101156k used, 9835004k free, 1287352k cached
如果没有引号,变量的内容将在shell的参数处理中显示出来。
答案 1 :(得分:1)
如果您要在顶部输出中查找特定信息,我会倾向于在存储之前过滤您要查找的内容,而不是捕获所有内容然后提取您需要的内容。
答案 2 :(得分:-1)
您可以通过sed将其传出来捕获并转换换行符,例如
top -n1 | sed 's/\(.*\)$/\1__CUSTOM_LINE_MARKER/g'
将在每行后输出CUSTOM_LINE_MARKER。尽管Rob Wells的回答可能是一种更好的方法。