从文本文件中获取数据

时间:2013-06-16 13:16:10

标签: regex perl sed awk pattern-matching

我正在尝试使用以下结构从文本文件中提取数据:

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

如您所见,该模式是一个包含Employee名称的表头,然后是包含其所有事务的表内容,然后重复该模式。

要提取交易,我这样做:

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.

2 个答案:

答案 0 :(得分:5)

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.

答案 1 :(得分:2)

GNU sed代码:

sed '/:/{s/[^:]\+://;H;x;s/.*\n//;d};G;s/\n//' file