【发布时间】:2016-08-11 07:51:24
【问题描述】:
我有一个 1,00,000 行的 JSON 文本文件。手动提取是不公平的。我写了一个 Perl 程序来读取文件的每一行,满足我的需要。
这是一个示例文本文件
示例.txt
"key": "Programming",
"doc_count": 1
"key": "Base",
"doc_count": 1,
"key": "Experience",
"doc_count": 1
"key": "Electrophoresis",
"doc_count": 1
我想单独使用双括号分隔的键值,例如 Programming、Base、Experience 和 Electrophoresis。
这是我尝试过的 Perl 代码:
ExtractKeyValue.pl
use strict;
use warnings;
my $file = $ARGV[0];
open my $info, $file or die "Could not open $file: $!";
while ( my $line = <$info> ) {
if ( $line =~ /"key(.*)",/ ) {
print $1;
print "\n";
}
}
close $info;
通过使用这个,我得到了这个输出
": "Programming
": "Base
": "Experience
": "Electrophoresis
我不想要前导冒号和空格。
我试过$line =~ /"key: "(.*)",/。但它不起作用。命令执行,但没有输出,也没有错误症状。
G:\ExtractKeyValue_Regex>perl ExtractKeyValue.pl Sample.txt > Output_Sample.txt
G:\ExtractKeyValue_Regex>
输出应该是这样的,
预期输出:
Programming
Base
Experience
Electrophoresis
我不明白为什么该模式不跟踪冒号 : 以及空格和双引号 "。
【问题讨论】:
-
您缺少报价:
"key":,而不是"key:。 -
请注意语言被称为Perl