Writing output into different files while processing file using AWK

Hi,

I am trying to do the following using AWK program.

  1. Read the input data file
  2. Parse the record and see if it contains errors
  3. If the record contains errors, then write it into Reject file, else, write into usual output file or display it on the screen

Here is what I have done -
BEGIN {FS=OFS="\n"}
{
fld1 = substr ($0, 1, 10)
fld2 = substr ($0, 11, 15)

if (fld1 == " ")
print "ERR : " fld1 "|" fld2 >> a.reject
else
print "ABC : " fld1 "|" fld2
}

When I execute the above awk, it is not creating a.reject file -- though there are input records with fld1 = blank. Kindly help.

Thanks and Regards,
Vidya

Apparently, fd1 is not returning an empty string.
Can you provide a sample of how does your input file looks like?

cheers,
Devaraj Takhellambam

A123456 11111
B123456 22222
C123456 33333
44444
D123456 55555

One more note, I also tried to check the length of fld1 (after trimming the contents) to write the record to reject file ... but still in vain :frowning:

Thanks and Regards,
Vidya

Ok..with this i/p file, your awk script will never create the file as it will always return something for fd1..
what sould be the content of the reject file..? How do you identify a line that is an error?

cheers,
Devaraj Takhellambam

Oops, I had posted one record with blank value for first field. Not sure, how it appeared different when I submitted the contents :frowning:
Well, let me try it in different way. Below are the contents of the file.

Line 1: A123456 11111
Line 2: B123456 22222
Line 3: C123456 33333
Line 4: 44444
Line 5: D123456 55555

In above example, line 4 does not contain contents for fld1 and hence should be written to Reject file. Does this help?

Thanks and Regards,
Vidya

Not sure, if you are looking for something like this:

 awk 'length($0) < 13 && substr($0,8,1)==""{print "ERR: " $0 > "reject.txt"}' filename

cheers,
Devaraj Takhellambam

Try this:

awk 'NF==1{print > "a.reject";next}{print}' file