用bash过滤输出并将过滤后的数据推入数组

时间:2021-10-26 15:41:25

I wasn't totally sure if I should have posted this here, serverfault or linux and unix but...

我不确定我是否应该在这里发布这个,serverfault或者linux和unix,但是…

What I'm trying to do here is take the output from this command:

这里我要做的是从这个命令中获取输出:

ps -eo pid -eo ecpu -eo command | sort -k 2 -r | grep -v PID | grep -i frmweb

用bash过滤输出并将过滤后的数据推入数组

... and apply a filter to which it only looks at processes that are using cpu. ( > 0 )

…并应用一个过滤器,它只查看正在使用cpu的进程。(> 0)

... and then take what's left and push the PIDs (first column) into an array.

…然后取出剩下的,将pid(第一列)推到一个数组中。

2 个解决方案

#1


2  

To put the process IDs in a bash array called nonzero:

将进程id放在一个称为nonzero的bash数组中:

nonzero=($(ps -eo pid -eo ecpu -eo command | sort -k 2 -r | awk '/frmweb/ && !/PID/ && $2+0>0{print $1}'))

awk commands have the form of condition {commands}. Here, the condition consists of three conditions and-ed together (&& means logical-and):

awk命令具有条件{命令}的形式。在这里,条件包含三个条件,并且一起(&& &表示逻辑的-和):

/frmweb/ && !/PID/ && $2+0>0
  • The first condition says that the line must contain frmweb.

    第一个条件是行必须包含frmweb。

  • The second requires that it must not contain PID

    第二个要求它不能包含PID

  • The third requires that the second column, denoted in awk by $2, be greater than zero. Awk can do both string and numeric comparisons. Although likely not necessary here, the use of addition, as in $2+0, forces the use of numeric comparison.

    第三行要求awk中用$2表示的第二列大于0。Awk可以同时进行字符串和数值比较。虽然在这里可能没有必要,但是使用加法,如$2+0,强制使用数值比较。

If all three conditions are met, the first column (the process ID) is printed via:

如果满足这三种条件,则通过以下方式打印第一列(流程ID):

print $1

Note that awk removes the need for the two grep commands.

注意,awk不需要两个grep命令。

#2


2  

array_of_pids=( $(your-pipeline | awk '$2 > 0.0 {print $1}') )  

#1


2  

To put the process IDs in a bash array called nonzero:

将进程id放在一个称为nonzero的bash数组中:

nonzero=($(ps -eo pid -eo ecpu -eo command | sort -k 2 -r | awk '/frmweb/ && !/PID/ && $2+0>0{print $1}'))

awk commands have the form of condition {commands}. Here, the condition consists of three conditions and-ed together (&& means logical-and):

awk命令具有条件{命令}的形式。在这里,条件包含三个条件,并且一起(&& &表示逻辑的-和):

/frmweb/ && !/PID/ && $2+0>0
  • The first condition says that the line must contain frmweb.

    第一个条件是行必须包含frmweb。

  • The second requires that it must not contain PID

    第二个要求它不能包含PID

  • The third requires that the second column, denoted in awk by $2, be greater than zero. Awk can do both string and numeric comparisons. Although likely not necessary here, the use of addition, as in $2+0, forces the use of numeric comparison.

    第三行要求awk中用$2表示的第二列大于0。Awk可以同时进行字符串和数值比较。虽然在这里可能没有必要,但是使用加法,如$2+0,强制使用数值比较。

If all three conditions are met, the first column (the process ID) is printed via:

如果满足这三种条件,则通过以下方式打印第一列(流程ID):

print $1

Note that awk removes the need for the two grep commands.

注意,awk不需要两个grep命令。

#2


2  

array_of_pids=( $(your-pipeline | awk '$2 > 0.0 {print $1}') )