连接并处理 top 命令输出中的两行

发布于 2024-12-12 06:14:00 字数 654 浏览 0 评论 0原文

我想加入并处理来自 top 命令的两行:

shell> top -p 1 -b -d 1 | egrep '^top|^Cpu'
top - 15:17:45 up 736 days,  4:32,  3 users,  load average: 0.06, 0.03, 0.00
Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

当尝试使用 awk 和 sed 命令时,我遇到了麻烦 - 没有产生输出。我将使用什么命令来使输出看起来像这样:

Time: 15:17:45 Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

这是一段可能有用的代码:

shell> echo 'top - 15:17:45 up 736 days,  4:32,  3 users,  load average: 0.06, 0.03, 0.00' | awk -F' up' '/^top/ {print "Time: " $1}' | sed 's/top - //'
Time: 15:17:45

I would like to join and process the two lines coming out of the top command:

shell> top -p 1 -b -d 1 | egrep '^top|^Cpu'
top - 15:17:45 up 736 days,  4:32,  3 users,  load average: 0.06, 0.03, 0.00
Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

When trying to use awk and sed commands, I run into trouble - no output is produced. What commands would I use to get the output to look like this:

Time: 15:17:45 Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

Here is a piece of code that could be useful:

shell> echo 'top - 15:17:45 up 736 days,  4:32,  3 users,  load average: 0.06, 0.03, 0.00' | awk -F' up' '/^top/ {print "Time: " $1}' | sed 's/top - //'
Time: 15:17:45

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

公布 2024-12-19 06:14:00

试试这个:

command | sed -n "N;s/top - /Time: /;s/up.*\n//;p" 

首先它读取秒行,然后用“Time:”替换“top - ”,最后删除从第一个换行符开始的所有内容。

输出:

Time: 15:17:45 Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

编辑:

试试这个:

top -p 1 -b -d 1 | awk '
    /^top/{a=$0}
    /^Cpu/{
        sub(/top - /,"Time:",a);
        sub(/up.*$/,"",a);
        printf "%s %s\n",a,$0;a=""}'

try this:

command | sed -n "N;s/top - /Time: /;s/up.*\n//;p" 

At first it reads in the seconds line, then it substitutes "top - " by "Time: ", finally it deletes everything from up unto the first line break.

Output:

Time: 15:17:45 Cpu(s):  0.7% us,  0.8% sy,  0.0% ni, 97.1% id,  1.3% wa,  0.0% hi,  0.0% si

EDIT:

Try this:

top -p 1 -b -d 1 | awk '
    /^top/{a=$0}
    /^Cpu/{
        sub(/top - /,"Time:",a);
        sub(/up.*$/,"",a);
        printf "%s %s\n",a,$0;a=""}'
甜尕妞 2024-12-19 06:14:00

这可能有效:

top -bn1 |sed -ru '1!d;N;s/^top -\s*(\S*).*\n/Time: \1 /'

sed -u 选项显然从输入文件加载最少量的数据,并更频繁地刷新输出缓冲区。
我只有 Top 的 Busybox 版本,所以我猜它会起作用。

This might work:

top -bn1 |sed -ru '1!d;N;s/^top -\s*(\S*).*\n/Time: \1 /'

The sed -u option apparently load minimal amounts of data from the input files and flushes the output buffers more often.
I only have the Busybox version of top so I am guessing it will work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文