首页 > 解决方案 > “Perl 的 if 语句过滤器”

问题描述

我正在使用 Perl 在大文件中搜索特定的经纬度数据。但我只想要属于包含“GT017”的数据的纬度/经度数据就在它之前

我已经成功抓取了以下数据类型呼号 Lat Long 时间戳

但是,我似乎无法将获取的数据限制为仅与呼号 GT017 相关的 Lat/Long/Timestamp

我已经尝试过 if 语句和子例程,但似乎都不允许我只打印与呼号 GT017 相关的 Lat/Long/timestamp

use strict;

#search for headers
my $find1= "GT017   ";
my $find2 = "timeStamp";
my $find3 = "latDD";
my $find4= "lonDD";

#above provides in response to my $find

#"callsign":"GT017   "
#"latDD":33.733200,
#"lonDD":-84.475667,
#"timeStamp":"2019-07-19T13:46:57.8Z",


open (NEW1, ">", "new1.txt" ) or die "could not open:$!";
open (FILE, "<", "test revab.txt") or die "could not open:$!";
while (<FILE>) {

#I want only a specific callsign's lat/long/timestamp printed

if ($find1 =~ /GT017/) {

print NEW1 if (/$find1/);
print NEW1 if (/$find2/);
print NEW1 if (/$find3/);
print NEW1 if (/$find4/);

}

}
close (FILE);
close (NEW1);

我从原始文件中得到一个带有每个纬度/经度/时间戳的大文件。

"latDD":33.733200,
"lonDD":-84.474266,
"timeStamp":"2019-07-19T13:46:58.22Z",
"latDD":33.733200,
"lonDD":-84.474266,
"timeStamp":"2019-07-19T13:46:58.8Z",
"latDD":33.708528,
"lonDD":-84.388506,
"timeStamp":"2019-07-19T13:46:58.33Z",

以下是每次出现“呼号”时我想要的:“GT017”,

"callsign":"GT017   ",
"timeStamp":"2019-07-19T13:47:50.0Z",
"latDD":33.781071,
"lonDD":-84.401736,

标签: perl

解决方案


这是一个例子:

my $find = '"callsign":"GT017   "';
while (<FILE>) {
    if (/\Q$find\E/) {
        print NEW1 $_;
        for (1..3) {
            print NEW1 scalar <FILE>;
        }
    }
}

这将打印带有呼号的行和以下 3 行。


推荐阅读