3

我正在尝试top通过 shell 脚本获取前 5 行命令,并且我需要将输出写入csv文件(我需要每 15 秒监视一次结果)。最后,我需要使用获得的数据表绘制图表。

top我得到了将前 5 行命令写入txt文件的 shell 脚本:

#!/bin/bash
echo "execution started.."

top -b -n 3 | sed -n '7,1p' >> out.txt

while [ true ]; do
    sleep 15
    echo "running.."
    top -b -n 3 | sed -n '8, 12p' >> out.txt
done

这是执行几次后的out.txt文件:

    PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
 3983 arun      20   0 1662480 309580  40936 S 26.3  6.4  13:36.00 gnome-shell
17907 arun      20   0  130020   1680   1172 R 10.5  0.0   0:00.03 top
 2016 root      20   0  221792  51172   9636 S  5.3  1.1   4:40.97 Xorg
11917 arun      20   0 7004884 570312  22040 S  5.3 11.7   0:48.83 java
    1 root      20   0   59732   7156   3992 S  0.0  0.1   0:02.71 systemd
 3983 arun      20   0 1662480 309580  40936 S 36.8  6.4  13:37.23 gnome-shell
 2016 root      20   0  221792  51172   9636 S 10.5  1.1   4:41.14 Xorg
 2720 mongod    20   0  624364  33716   5200 R  5.3  0.7   1:44.36 mongod
17918 arun      20   0  130020   1676   1172 R  5.3  0.0   0:00.02 top
    1 root      20   0   59732   7156   3992 S  0.0  0.1   0:02.71 systemd
 3983 arun      20   0 1662480 309580  40936 S 25.0  6.4  13:38.60 gnome-shell
 2720 mongod    20   0  624364  33672   5160 S  5.0  0.7   1:44.46 mongod
12081 arun      20   0 2687496 314248  21436 S  5.0  6.5   3:05.51 java
17922 arun      20   0  130020   1680   1172 R  5.0  0.0   0:00.02 top
    1 root      20   0   59732   7156   3992 S  0.0  0.1   0:02.71 systemd

但我需要csv格式的相同数据。我试图通过将输出文件名指定为out.csv来做到这一点来做到这一点!但这没有用。(因为它的格式不正确,所以整个数据都在第一个 shell 中!)

您能否提供将相同输出写入csv文件的解决方案?

4

1 回答 1

11

If you want to trim runs of whitespace and replace them with commas, try

top -b -n 3 | sed -n '8, 12{s/^ *//;s/ *$//;s/  */,/gp;};12q'

The sed script performs the following substitutions on lines 8 through 12:

  • Replace any leading space with nothing (otherwise you get an empty first column when the PID is right-aligned).
  • Replace any trailing spaces with nothing (similarly to avoid empty fields after the data).
  • Replace any remaining runs of adjacent spaces with a comma. Print this line.

Finally, on line 12, we are done, so we quit sed.

The shell does not pay any attention to the name of the file you are redirecting into and generally, file extensions on Unix are informal decorations, not file type specifiers like they are on some platforms.

You could do echo hello >outputfile.ps and the output would still be text, not PostScript (or a number of other possible interpretations of the .ps file extension). In any event, the echo command does not know that it is being redirected, because that is handled by the shell before the command runs, anyway. (Well, echo is a shell built-in, so in theory there could be some coordination in this case.)

于 2016-01-25T12:23:45.193 回答