首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Perl从文件中提取特定数据?

如何使用Perl从文件中提取特定数据?
EN

Stack Overflow用户
提问于 2021-05-27 17:12:54
回答 3查看 390关注 0票数 2

我有需要从文件中提取的数据,我现在需要的行是名称、位置和主机。这是摘录的例子。我将如何将这些行放入一个单独的文件中?我有原始文件和我想要创建的新文件作为输入/输出文件,输出文件中包含数千个设备,它们都是与我的示例中相同的格式。

代码语言:javascript
复制
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(strftime);

#names of files to be input output

my $inputfile = "/home/nmis/nmis_export.csv";
my $outputfile = "/home/nmis/nmis_data.csv";
open(INPUT,'<',$inputfile) or die $!;
open(OUTPUT, '>',$outputfile) or die $!;
my @data = <INPUT>;
close INPUT;
my $line="";
foreach $line (@data)
{

======Sample Extract=======

代码语言:javascript
复制
    **"group" : "NMIS8",
         "host" : "1.2.3.4",
         "location" : "WATERLOO",
         "max_msg_size" : 1472,
         "max_repetitions" : 0,
         "model" : "automatic",
         "netType" : "lan",
         "ping" : 1,
         "polling_policy" : "default",
         "port" : 161,
         "rancid" : 0,
         "roleType" : "access",
         "serviceStatus" : "Production",
         "services" : null,
         "threshold" : 1,
         "timezone" : 0,
         "version" : "snmpv2c",
         "webserver" : 0
      },
      "lastupdate" : 1616690858,
      "name" : "test",
      "overrides" : {}
},
   {
      "activated" : {
         "NMIS" : 1
      },
      "addresses" : [],
      "aliases" : [],
      "configuration" : {
         "Stratum" : 3,
         "active" : 1,
         "businessService" : "",
         "calls" : 0,
         "cbqos" : "none",
         "collect" : 0,
         "community" : "public",
         "depend" : [
            "N/A"
         ],
         "group" : "NMIS8",
         "host" : "1.2.3.5",
         "location" : "WATERLOO",
         "max_msg_size" : 1472,
         "max_repetitions" : 0,
         "model" : "automatic",
         "netType" : "lan",
         "ping" : 1,
         "polling_policy" : "default",
         "port" : 161,
         "rancid" : 0,
         "roleType" : "access",
         "serviceStatus" : "Production",
         "services" : null,
         "threshold" : 1,
         "timezone" : 0,
         "version" : "snmpv2c",
         "webserver" : 0
      },
      "lastupdate" : 1616690858,
      "name" : "test2",
      "overrides" : {}
   },**
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-05-27 18:31:31

为此,我将使用jq,而不是Perl。只需查询JSON文档即可。这就是jq的目的。你可以见这里的一个例子

我创建的jq查询就是这个,

代码语言:javascript
复制
.[] | {name: .name, group: .configuration.group, location: .configuration.location}

这会分解成

代码语言:javascript
复制
.[] # iterate over the array
  | # create a filter to send it to
  {  # that produces an object with the bellow key/values
    .name,
    group: .configuration.group,
    location: .configuration.location
  }

它提供了这样的输出,

代码语言:javascript
复制
{
  "name": "test2",
  "group": "NMIS8",
  "location": "WATERLOO"
}
{
  "name": "test2",
  "group": "NMIS8",
  "location": "WATERLOO"
}

您可以使用它生成一个csv。

代码语言:javascript
复制
jq -R '.[] | [.name, .configuration.group, .configuration.location] | @csv' ./file.json

或者这个来生成一个带有头的csv,

代码语言:javascript
复制
jq -R '["name","group","location"], (.[] | [.name, .configuration.group, .configuration.location]) | @csv' ./file.json
票数 3
EN

Stack Overflow用户

发布于 2021-05-27 18:18:43

因为有JSON,所以应该使用JSON解析器来解析它。JSON::PP是标准Perl发行版的一部分。如果您想要更快的东西,可以从CPAN安装其他的东西。

更新:--我在回答中包含了一个指向JSON::PP的链接。你跟踪那个链接了吗?如果是这样的话,您就会看到模块的文档。它包含了更多关于如何使用模块的信息,比我在回答中包含的更多。

但有可能你需要更高层次的信息。文件上说:

:PP是一个纯perl JSON解码器/编码器

但也许你不知道那是什么意思。这里有个底漆。

JSON是一种用于存储复杂数据结构的文本格式。这种格式最初在Javascript中使用(缩写为"JavaScript对象表示法“),但现在它是几乎所有编程语言都使用的标准。

您很少想在程序中实际处理JSON。JSON文档只是文本和操作,需要一些复杂的正则表达式。在处理JSON时,通常的方法是将JSON“解码”到程序中的数据结构中。然后,您可以随意地操作数据结构,在此之前(可以选择)将数据结构“编码”回JSON,这样您就可以将其写入输出文件(在您的示例中,您不需要这样做,因为您希望将输出作为CSV)。

因此,Perl JSON库只需要做两件事:

  1. 获取一些JSON文本并将其解码为Perl数据结构
  2. 采用Perl数据结构并将其编码为JSON文本

如果您查看JSON::PP文档,您将看到它包含两个函数,encode_json()decode_json(),它们执行我前面描述的操作。还有一个OO接口,但是我们不要太快地把事情复杂化。

因此,您的程序现在需要有以下步骤:

  1. 从输入文件读取JSON
  2. 将JSON解码为Perl数据结构
  3. 遍历Perl数据结构以提取所需的项。
  4. 将所需的项写入您的输出文件(对此案文:CSV将是有用的)

话虽如此,但在我看来,user157251建议的解决方案确实是一个更好的主意。

票数 3
EN

Stack Overflow用户

发布于 2021-05-27 20:58:51

您可以为此使用JSON发行版。一举读取整个文件,将整个JSON字符串放入标量(而不是将其放入数组并迭代),然后简单地将字符串解码为Perl数据结构:

代码语言:javascript
复制
use warnings;
use strict;

use JSON;

my $file = 'file.json';

my $json_string;

{
    local $/;              # Locally reset line endings to nothing

    open my $fh, '<', $file or die "Can't open file $file!: $!";

    $json_string = <$fh>;  # Slurp in the entire file
}

my $perl_data_structure = decode_json $json_string;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67726957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档