【问题标题】:How to retrieve data from log files using linux commands and add to array如何使用 linux 命令从日志文件中检索数据并添加到数组
【发布时间】:2018-07-16 12:08:17
【问题描述】:

我有一个包含这样内容的日志文件

2018/01/14 12:27:27|get_offers|ok|1678537191|64.233.173.132|info=wifi
2018/01/14 12:27:27|get_offers|ok|1678537191|64.233.173.132|info=wifi
2018/01/14 12:27:27|get_offers|ok|1678537191|64.233.173.132|info=wifi

我正在尝试一一分别检索数据/报价/状态/号码/ IP。 我正在为此使用 PHP Yii 框架,并在运行 linux 命令的程序中使用。

命令

 $dateCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $1}'";
 $descCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $2}'";
 $statusCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $3}'";
 $mobileCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $4}'";
 $ipCmd = "cat " . $file_names_str . "| awk -F '|' '{ print $5}'";

执行部分

 $date = shell_exec($dateCmd);
 $desc = shell_exec($descCmd);
 $status = shell_exec($statusCmd);
 $mobile = shell_exec($mobileCmd);
 $ip = shell_exec($ipCmd);

最后我想要一个这样的数组。并编码为 JSON。以下数组包含虚拟数据。

$rec = [
            [
                'date' => '2018-02-01',
                'desc' => 'test descrip',
                'status' => 'true',
                'mobile' => '2145786695',
                'ip' => '127.168.0.1',
            ],
            [
                'date' => '2018-02-01',
                'desc' => 'test descrip2',
                'status' => 'true',
                'mobile' => '2145786695',
                'ip' => '127.168.0.1',
            ],
            [
                'date' => '2018-02-01',
                'desc' => 'test descrip2',
                'status' => 'true',
                'mobile' => '2145786695',
                'ip' => '127.168.0.1',
            ],

        ];


        $enc =  CJSON::encode($rec);
        echo $enc;

但在这种情况下,它不会按我的意愿检索数据。我是 linux 新手,我只想像这张图片一样逐行获取记录。

请帮我解决这个问题。

【问题讨论】:

  • 我不会像这样在 linux 和 php 之间切换:如果你有一个有效的 csv 文件,其中分隔符是 | 符号,使用 fgetcsv() 读取和解析可能更容易它。
  • 为什么这么复杂 - 为什么不在一个 PHP 脚本中完成所有事情呢?就像在这个例子中一样:stackoverflow.com/questions/14574944/…

标签: php arrays linux logging


【解决方案1】:

一个简单的 PHP 解决方案:

$lines = file("logfile.log");
foreach ($lines as $line)
{
  $parts = explode("|", $line);
  $result[] = [
    'date' => $parts[0],
    'desc' => $parts[1],
    'status' => $parts[2],
    'mobile' => $parts[3],    
    'ip' => $parts[4],
    'info' => $parts[5]
  ];
}

header("Content-type:application/json");
echo json_encode($result);

【讨论】:

  • 这些问题有一个延伸。有多个日志文件。我想通过运行与您的答案相同的文件并添加到一个数组来立即执行此操作。我该怎么做?
  • 您可以使用 glob() 读取符合特定条件的所有文件的数组。然后遍历它们并将内容放在每个文件的子数组中。这是您需要为新循环添加的内容:foreach (glob("*.log") as $filename),在循环中将 $result[] = 更改为 $result[$filename][] =
猜你喜欢
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
相关资源
最近更新 更多