Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    [SOLVED] dynamic output in awk

    Hi all;

    I need to re-direct the output within an awk script, but not to already known, fixed filenames. The output file names depend on values of the fields. For example (the actual problem is surely more complicated), if, on a given line, the second field is DATA, the third is 1984, I would like to print some information in a file called output_DATA_1984. This could/would change in the following line of the same input file. Such things are pretty easy in bash, put I cannot do it in awk, as I can only find manual references for redirecting output to fixed filenames between double quotes.

    Thanks a lot in advance.

  2. #2
    It's even easier with awk:

    % cat infile 
    col1 DATA 1984
    col1 DATA2 1985
    col1 DATA3 1993
    % awk '{
      f && close(f)
      f = "output" OFS $2 OFS $3
      print > f
      }' OFS=_ infile
    % head output_DATA*
    ==> output_DATA2_1985 <==
    col1 DATA2 1985
    ==> output_DATA3_1993 <==
    col1 DATA3 1993
    ==> output_DATA_1984 <==
    col1 DATA 1984

  3. #3
    Thanks a lot!

    I was able to implement it on my script (with the due modifications), and it worked perfectly. In fact I need to write to different folders, and it seems that awk doesn't create them if needed, but that I will solve in bash. [edit: just checked and found it is quite easy to, within awk, check for existence and create the folders if needed... ]

    I still cannot understand it perfectly, but enough to use the idea. It is really simple. Way better than the while read LINE ... and one million cut sed grep commands...

    Now just hope it is as less time consuming as I presumed.
    Last edited by mrz; 02-28-2011 at 01:54 AM.

  4. $spacer_open

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts