【发布时间】:2014-08-27 21:35:20
【问题描述】:
我有一个问题。我想编写一个 perl 脚本来将 Mailgun 输出解析为 csv 格式。我假设'split' 和'join' 函数在这个过程中可以正常工作。以下是一些示例数据:
样本数据
{
"geolocation": {
"city": "Random City",
"region": "State",
"country": "US"
},
"url": "https://www4.website.com/register/1234567",
"timestamp": "1237854980723.0239847"
}
{
"geolocation": {
"city": "Random City2",
"region": "State2",
"country": "mEXICO"
},
"url": "https://www4.website2.com/register/ABCDE567",
"timestamp": "1237854980723.0239847"
}
期望的输出
“城市”、“地区”、“国家”、“网址”、“时间戳”
"随机城市","州","US","https://www4.website.com/register/1234567","1237854980723.0239847"
"Random City_2","State_2","mEXICO","www4.website2.com/ABCDE567","1237854980723.0239847_2"
我的目标是获取我的示例数据并将所需的输出创建为逗号分隔的 CSV 文件。我不确定该怎么做。通常我会尝试在批处理文件中使用一系列单行代码来解决这个问题,但我更喜欢 perl 脚本。真实数据将包含更多信息。但是,只要弄清楚如何解析一般结构就可以了。
这是我在批处理文件中的内容。
代码
perl -p -i.bak -e "s/(,$|,+ +$|^.*?{$|^.*?}.*?$|^.*?],.*?$)//gi" file.txt
rem Removes all unnecessary characters and lines with { and }. ^
perl -p -i.bak -e "s/(^ +| +$)//gi" file.txt
perl -p -i.bak -e "s/^\n$//gi" file.txt
rem Removes all blank lines in initial file. Next one-liner takes care of trailing and beginning
rem whitespace. The file is nice and clean now.
perl -p -e "s/(^\".*?\"):.*?$/$1/gi" file.txt > header.txt
rem retains only header info and puts into 'header.txt' ^
perl -p -e "s/^\".*?\": +(\".*?\"$)/$1/gi" file.txt > data.txt
rem retains only data that is associated with each field.
perl -p -i.bak -e "s/\n/,/gi" data.txt
rem replaces new line character with ',' delimiter.
perl -p -i.bak -e "s/^/\n/gi" data.txt
rem drops data down a line
perl -p -i.bak -e "s/\n/,/gi" header.txt
rem replaces new line character with ',' delimiter.
copy header.txt+data.txt report.txt
rem copies both files together. Since there is the same amount of fields as there are data
rem delimiters, the columns and headers match.
我的输出
“城市”、“地区”、“国家”、“网址”、“时间戳”
"随机城市","州","US","https://www4.website.com/register/1234567",1237854980723.0239847
这可以解决问题,但精简的脚本会更好。不同的情况会影响这个批处理脚本我需要更可靠的东西。有什么建议吗??
【问题讨论】:
-
使用JSON。
标签: perl batch-file join split mailgun