gpt4 book ai didi

regex - 从文本文件中获取数据

转载 作者:行者123 更新时间:2023-12-01 10:00:17 24 4
gpt4 key购买 nike

我正在尝试从具有以下结构的文本文件中提取数据:

Employee: John C.
2013-01-01 10 $123
2013-01-02 12 $120
2013-01-03 8 $150
Employee: Michael G.
2013-01-01 5 $13
2013-01-05 11 $20
2013-01-10 2 $155

如您所见,该模式是一个包含员工姓名的表头,然后是包含其所有交易的表内容,然后重复该模式。

为了提取交易,我这样做:

awk '/^  [A-Z]/{print $1"\t"$2"\t"$3}'

这给出了这个结果:

  2013-01-01  10  $123
2013-01-02 12 $120
2013-01-03 8 $150
2013-01-01 5 $13
2013-01-05 11 $20
2013-01-10 2 $155

我如何创建返回此的两遍提取:

  2013-01-01  10  $123  John C.
2013-01-02 12 $120 John C.
2013-01-03 8 $150 John C.
2013-01-01 5 $13 Michael G.
2013-01-05 11 $20 Michael G.
2013-01-10 2 $155 Michael G.

最佳答案

awk 的一种方式:

awk -F":" '/^Employee/{a=$NF;next}{print $0,a}' file

测试:

$ cat file
Employee: John C.
2013-01-01 10 $123
2013-01-02 12 $120
2013-01-03 8 $150
Employee: Michael G.
2013-01-01 5 $13
2013-01-05 11 $20
2013-01-10 2 $155
$ awk -F":" '/^Employee/{a=$NF;next}{print $0,a}' file
2013-01-01 10 $123 John C.
2013-01-02 12 $120 John C.
2013-01-03 8 $150 John C.
2013-01-01 5 $13 Michael G.
2013-01-05 11 $20 Michael G.
2013-01-10 2 $155 Michael G.

关于regex - 从文本文件中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17133749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com