Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get data from a text file

I'm trying to extract data from a text file with the following structure:

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

As you can see, the pattern is a table header containing the Employee name and then table content containing all of its transactions, then the pattern repeats.

To extract transactions I do this:

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

This gives this result:

  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

How can I create a two pass extraction that returns this:

  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.
like image 709
leonardorame Avatar asked Nov 24 '25 01:11

leonardorame


2 Answers

One way with awk:

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

Test:

$ 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.
like image 191
jaypal singh Avatar answered Nov 26 '25 17:11

jaypal singh


Code for GNU sed:

sed '/:/{s/[^:]\+://;H;x;s/.*\n//;d};G;s/\n//' file
like image 32
captcha Avatar answered Nov 26 '25 17:11

captcha