如何正确地将unix top命令输出保存到变量中?
我必须将 top 命令的输出保存到一个变量中,然后执行以下操作:
myvar=`top -b -n1 | head -n 18`
问题是它似乎忽略了返回字符,因此当我回显 $myvar
的内容时,我看到这样的内容:
top - 15:15:38 up 745 days, 15:08, 5 users, loadaverage: 0.22, 0.27, 0.32 Tasks: 总共 133 个,1 个正在运行,132 个正在睡眠,0 个停止,0 个僵尸 Cpu (s):6.4% us、1.6%sy、0.0% ni、91.7% id、0.3% wa、0.0% hi、0.0% si 内存:总计 2074716k、已用 2038716k、可用 36000k、84668k 缓冲区 交换:总计 4192924k、107268k使用过,4085656k 等...
如何正确保存所有顶级数据?
I've got to save the output of the top command into a variable and I do this:
myvar=`top -b -n1 | head -n 18`
The problem is that it seems to be ignoring the return characters, so when I echo the content of $myvar
I see something like:
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...
How can I save all top data correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意差异:
输出:
如果没有引号,变量的内容将在 shell 的参数处理中进行处理。
Notice the difference:
Output:
Without the quotes, the contents of the variable are ground up in the shell's argument processing.
如果您正在顶部输出中查找特定的信息,我倾向于在存储之前过滤顶部输出以查找您要查找的内容,而不是捕获所有内容,然后提取您需要的内容。
If you are looking for a particular piece of info within the top output i'd be inclined to filter the top output for what you're looking for before storing it rather than capture everything and then extract what you need.
您可以通过 sed 将其输出以捕获并转换换行符,例如
将在每行之后输出 CUSTOM_LINE_MARKER 。尽管罗布·威尔斯上面的回答可能是更好的方法。
You could pipe it out through sed to catch and transform the line breaks, e.g.
will output the CUSTOM_LINE_MARKER after every line. though Rob Wells answer above is probably a better approach.