gpt4 book ai didi

php解析ps aux | grep ...结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:48:08 24 4
gpt4 key购买 nike

我有一个系统脚本,它运行并将“ps aux | grep utilities”的结果通过管道传输到一个文本文件,并对文本文件进行 chown,以便网络服务可以读取该文件并在我的网络应用程序中显示结果。

这是原始结果的示例:

user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities

当我的 php 脚本解析这个文本文件时,我只需要提取以下内容(仅作为示例):

cust1
cust3
cust4
cust89
cust435
cust16

我已经尝试了很多不同的笨拙方法,但似乎没有什么效果很好。我在下面列出的方法有效,但有时也会抓取垃圾,因为一行中的“空格”数量会随着变化而爆炸。

public function showProcesses() {
$lines = file(DIR_LOGGER_ROOT . "dashboard/currentlyPosting.txt");
$results = array();
$i = 0;
foreach($lines as $line) {
if (preg_match("/php/i", $line)) {
$userProcess = explode(" ", $line);
if($userProcess[29] != "0:00" && strlen($userProcess[29]) < 20) {
$results[$i] = $userProcess[29];
$i++;
}
}
}
return $results;
}

你们中的一些人可以为此发布优雅的解决方案吗?我正在努力学习更好的做事方式,希望得到指导。

最佳答案

你可以使用 preg_split而不是 explode 并在 [ ]+ 上拆分(一个或多个空格)。但我认为在这种情况下你可以选择 preg_match_allcapturing :

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

模式匹配一​​个空格,php,更多的空格,一串非空格(路径),更多的空格,然后捕获下一个非空格的字符串。第一个空格主要是为了确保您不会将 php 作为用户名的一部分进行匹配,而实际上只是作为命令。

捕获的替代方法是 PCRE 的“保留”功能。如果你在模式中使用 \K,它之前的所有内容都会在匹配中被丢弃:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

关于php解析ps aux | grep ...结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com