regex - 当有多个字段分隔符时,使用 AWK 忽略字段中的逗号
问题描述
awk
我想用或解析像下面这样的 CSV 记录gawk
。
字段由逗号分隔,但最后一个字段 ( $6
) 是特殊的,因为它实际上由子字段组成。这些子字段由 # 分隔,作为字段分隔符(或者,准确地说是“.#”)。这本身不是问题:我可以awk -F'(,)|(. # )'
用来设置替代字段分隔符。
但是,在最后一个字段中也有需要忽略的杂散逗号。
有没有办法解决这个问题awk
,也许使用 FPAT?
样本记录:
"http://publications.europa.eu/resource/cellar/3befa3c3-a9af-4dac-baa2-92e95cb6e3ab","http://publications.europa.eu/resource/cellar/3befa3c3-a9af-4dac-baa2-92e95cb6e3ab.0002","EU:C:1985:443","61984CJ0239","Gerlach","Judgment of the Court (Third Chamber) of 24 October 1985. # Gerlach & Co. BV, Internationale Expeditie, v Minister van Economische Zaken. # Reference for a preliminary ruling: College van Beroep voor het Bedrijfsleven - Netherlands. # Article 41 ECSC - Anti-dumping duties. # Case 239/84."
解决方案
使用FPAT
中的功能gnu-awk
,您也许可以做到这一点。我们使用FPAT
匹配所有双引号字段或逗号分隔的字段。/\. # /
最后,我们使用正则表达式模式分割最后一个字段。
s='"http://publications.europa.eu/resource/cellar/3befa3c3-a9af-4dac-baa2-92e95cb6e3ab","http://publications.europa.eu/resource/cellar/3befa3c3-a9af-4dac-baa2-92e95cb6e3ab.0002","EU:C:1985:443","61984CJ0239","Gerlach","Judgment of the Court (Third Chamber) of 24 October 1985. # Gerlach & Co. BV, Internationale Expeditie, v Minister van Economische Zaken. # Reference for a preliminary ruling: College van Beroep voor het Bedrijfsleven - Netherlands. # Article 41 ECSC - Anti-dumping duties. # Case 239/84."'
awk -v FPAT='"[^"]*"|[^,]+' '{
# loop through all fields except last one
for (i=1; i<NF; ++i)
print i, $i
# split last field using /\. # / regex and print each token
for (j=1; j<split($NF, a, /\. # /); ++j)
print i+j-1, a[j]
}' <<< "$s"
1 "http://publications.europa.eu/resource/cellar/3befa3c3-a9af-4dac-baa2-92e95cb6e3ab"
2 "http://publications.europa.eu/resource/cellar/3befa3c3-a9af-4dac-baa2-92e95cb6e3ab.0002"
3 "EU:C:1985:443"
4 "61984CJ0239"
5 "Gerlach"
6 "Judgment of the Court (Third Chamber) of 24 October 1985
7 Gerlach & Co. BV, Internationale Expeditie, v Minister van Economische Zaken
8 Reference for a preliminary ruling: College van Beroep voor het Bedrijfsleven - Netherlands
9 Article 41 ECSC - Anti-dumping duties
推荐阅读
- azure-storage - 在我的存储帐户中创建了许多 4 个字符的存储容器
- google-cloud-platform - GCP DataPrep-移动窗口
- android - 在android studio中单击图像视图后如何选择按钮
- r - 使用 NeuralNet 的分类/治疗概率
- django - Django:在form_valid中调用类函数
- mysql - 在mysql中创建一个简单的存储过程
- php - 为什么添加 htaccess 规则后,特定页面中的 XHR 调用不起作用?
- ios - 无法通过 XCode 9.4 上的 CoreSimulator 生成问题启动 IBCocoaTouchImageCatalogTool
- java - java - 如何在有时间限制的情况下强制终止java中的线程?
- c++ - Graph-tool:在 Linux 中编译并连接到本地 CGAL 库?(没有须藤)