Solved Redirect AWK Output into different files

May 20, 2012 at 03:24:49
Specs: Solaris
Hi Experts,

I am trying to redirect awk ouput into different files based on the entry code but when I execute my script, if gives me below error.

Sample Input:

ENTRY G1L
RMSP_Pex4 1254 17440626
RMSP_Pex3 1028 14184119
SEDZ_Pqa 926 12768075
RMSP_Pex1 1550 21605835
TLEC_Jsp 502 6959482
POIT_Jdp 282 3783705
RMSP_Pex2 528 7291222
TOTAL 84033064
TOTAL 6070 84033064
ENTRY G1R
RMSP_Pex4 1254 17440626
RMSP_Pex3 1028 14184119
SEDZ_Pqa 926 12768075
RMSP_Pex1 1550 21605835
TLEC_Jsp 502 6959482
POIT_Jdp 282 3783705
RMSP_Pex2 528 7291222
TOTAL 84033064


My Script:

dt1=`TZ=CST+24 date +%Y%m%d`
cat SAMPLE_ENTRY.txt2 |awk '{
if($1 ~ /ENTRY/)
code=$2
if($1 !~ /ENTRY/ && NF == 3 && $1 !~/TOTAL/)
{
printf("%-19s %6s %12s %s\n", $1, $2, $3, code) >> code_${dt1}.txt
}
if($1 ~ /TOTAL/ && NF == 3)
{
printf("%-19s %6s %12s %s\n", $1, $2, $3, code) >> code_${dt1}.TOTAL.txt
}
if($1 ~ /TOTAL/ && NF == 2)
{
printf("%-19s %19s %s\n", $1, $2, code)
} >> code_${dt1}.TOTAL.txt
}'


Expected Output

I am expecting five different files but it gives me some syntax errors.

Does anyone try to do the same script? How did you manage to create the desired output? Any inputis higly appreciated.

Thanks and Regards,
Amiti


See More: Redirect AWK Output into different files

Report •

#1
May 20, 2012 at 14:14:35
✔ Best Answer
The syntax you are using for embedding shell variables is not correct. This link deals with awk and shell variables:

http://www.tek-tips.com/faqs.cfm?fi...

#!/bin/ksh

dt1=`TZ=CST+24 date +%Y%m%d`

nawk ' # I use nawk for Solaris.  You probably require awk
{
if(NR == 1)
   { # build the file names on the first record
   fn="code_"dt1".txt"
   fn1="code_"dt1"TOTAL.txt"
   }

if($1 ~ /ENTRY/)
   code=$2

if($1 !~ /ENTRY/ && NF == 3 && $1 !~/TOTAL/)
   printf("%-19s %6s %12s %s\n", $1, $2, $3, code) >> fn

if($1 ~ /TOTAL/ && NF == 3)
   printf("%-19s %6s %12s %s\n", $1, $2, $3, code) >> fn1

if($1 ~ /TOTAL/ && NF == 2)
   printf("%-19s %19s %s\n", $1, $2, code) >> fn1

}' dt1="$dt1" SAMPLE_ENTRY.txt2


Report •
Related Solutions


Ask Question