解析Perl中的文本文件并将信息存储在JSON中
问题描述:
所以,我有这个文件,它包含不同文件的不同路径,以及文件类型随着行数的变化而变化。像这样的东西解析Perl中的文本文件并将信息存储在JSON中
abc123:
Files Changed: lines: new deleted unchanged
some/path/to/file.c 15 0 4234
some/other/file.h 1 0 223
some/other/path/to/file2 3 1 3
Files Created: lines: new deleted unchanged
some/path/to/file.c 3 1 3
Files Changed: lines: new deleted unchanged
some/other/path/to/file 2 2 234
我需要找到一个简单的方法来解析这个。我真的不在乎线路的变化(新的,删除的,不变的)。我想要的是有一个JSON。事情是这样的:
{
"abc123":{
"Files Changed:": [
"some/path/to/file.c",
"some/other/file.h",
"some/other/path/to/file",
"some/other/path/to/file2"
],
"Files Created:":[
"some/path/to/file.c"
]
}
}
比较困难的部分是试图分析文本文件我想要的东西,可以用什么文件给你工作。我所知道的肯定可能会有效的是任何具有'/'的文件都是一个文件字符串,但我不知道如何告诉它它是'File Changed'还是'File Created'。此外,该文件可能具有像'文件已删除''文件链接'与其相应的文件路径。如何实现这一点的任何帮助将不胜感激。
答
只要行首的空白符合,就很容易实现。您需要逐行阅读,并记住您在哪个级别上看到的内容。
在下面的代码中,我假设每个级别有两个缩进空格。因为这看起来像是某种版本控制的总结,我打电话
- 压痕的第0级ABC123
$commit
, - 和1级已经做了下面列出的文件
$operation
。 - 第二级包含文件名。
use strict;
use warnings;
use JSON 'to_json';
my $commit; # abc123
my $operation; # Files Changed, Files Created
my $data; # this is the target
while (my $line = <DATA>) {
if ($line =~ /^(\S+):/) {
# line contains a commit
$commit = $1;
next;
}
if ($line =~ /^\s\s([^:]+):/) {
# line contains an operation
$operation = $1;
next;
}
if ($line =~ /^\s\s\s\s(\S+)/) {
# this is a filename
push @{ $data->{$commit}->{$operation} }, $1;
}
}
print to_json $data;
__DATA__
abc123:
Files Changed: lines: new deleted unchanged
some/path/to/file.c 15 0 4234
some/other/file.h 1 0 223
some/other/path/to/file2 3 1 3
Files Created: lines: new deleted unchanged
some/path/to/file.c 3 1 3
Files Changed: lines: new deleted unchanged
some/other/path/to/file 2 2 234
这将产生以下输出。
{"abc123":{"Files Changed":["some/path/to/file.c","some/other/file.h","some/other/path/to/file2","some/other/path/to/file"],"Files Created":["some/path/to/file.c"]}}
+0
你是一个救世主!没有想到空间。有效!谢谢! –
如果行开头的空格是一致的,这很容易实现。你只需要逐行阅读,并记住你在最后一个级别上看到了什么。这是git输出吗? – simbabque