【问题标题】:get data from a text file从文本文件中获取数据
【发布时间】:2013-06-12 14:15:28
【问题描述】:

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

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.

【问题讨论】:

    标签: regex perl sed awk pattern-matching


    【解决方案1】:

    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.
    

    【讨论】:

      【解决方案2】:

      GNU sed 代码:

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

      【讨论】:

        猜你喜欢
        • 2011-04-04
        • 2016-02-08
        • 2015-04-07
        • 1970-01-01
        • 2019-05-15
        • 2020-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多