在 unix 命令行命令中使用变量
我正在尝试使用找到的步骤计算处理器的 CPU 负载 这里。我设法做到了这一点:
cat /proc/stat | head -n 1 | awk '{print ($5+$6, $2+$3+$4+$7+$8+$9)}' | awk '{print($1,$1+$2)}'
这给了我我需要的价值观。但是,我需要在一秒钟后计算相同的值,然后使用这两个结果来计算最终负载。这意味着,我需要做这样的事情:
cat /proc/stat | calculate something | awk '{print($1,$1+$2)}' ; sleep for a second; calculate again; use both of the results
有没有办法在第一个 awk 调用中保存变量 $1 和 $1+$2 ,以便我以后可以使用它们?我无法使用 bash 脚本,它需要在命令行中完成。
I am trying to calculate the CPU load of a processor using the steps found here. I managed to do this:
cat /proc/stat | head -n 1 | awk '{print ($5+$6, $2+$3+$4+$7+$8+$9)}' | awk '{print($1,$1+$2)}'
This gives me the values I need. However, I need to calculate the same values a second later and then use both of these results to calculate the final load. That means, that I need to do something like this:
cat /proc/stat | calculate something | awk '{print($1,$1+$2)}' ; sleep for a second; calculate again; use both of the results
Is there a way for me to save the variables $1 and $1+$2 in the first awk call, so that I can use them later? I cannot use a bash script, it needs to be done in a command line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无需在现有命令的管道中拼凑对工具的单独调用。这:
可以重写为这样:
听起来您可能想做的是这样的:
如果您无法根据该信息做您想做的任何事情,那么编辑您的问题以提供更清晰的要求和一些简洁的信息、可测试、真正具有代表性的样本输入/输出。
You don't need to piece together separate calls to tools in a pipeline for your existing command. This:
can be rewritten as this:
It sounds like what you might want to do is something like:
If you can't do whatever it is you're trying to do given that information then edit your question to provide clearer requirements and some concise, testable, truly representative sample input/output.
一个简单的解决方案是首先创建完整的输入,然后使用
awk
处理它。我们首先定义cpuLoad
bash
函数以 1 秒的间隔捕获两个 CPU 负载:然后我们可以提供一个
awk
脚本来实现精确的您引用的已接受答案的算法:但我们可以简化很多:
最后,我们可以将所有这些封装在 bash 函数中:
A simple solution would be to create the complete input first and process it with
awk
next. We first define thecpuLoad
bash
function to capture two CPU loads with a 1 second interval:Then we can feed an
awk
script that implements the exact algorithm of the accepted answer you cite:But we can simplify a lot:
And finally, we can encapsulate all this in the
bash
function: