Insert missing field using perl,sed,awk

sample file (comma as field separators)

MessageFlow,1,BusIntBatchMgr,a
OOBEvent,1,BusIntBatchMgr,a
TaskEvents,1,,a
MTTrace,1,,a
MTWarning,,1,a
MessageFlow,1,Batch,a
OOBEvent,1,Batch,a
TaskEvents,1,,a
EAISAPIdocWizard,1,BusIntMgr,a
EAISAPBAPIWizard,1,BusIntMgr,a
EAISiebelWizard,1,BusIntMgr,a

In the above file, some lines have empty field3. The requirement is to fill the missing field3 with the previous field3 value.
i.e. In line 3,4&5, field3 should have the value BusIntBatchMgr. In line 8, field3 should have the value Batch.

Please let me know how to achieve this in PERL, SED or AWK (any combination). Please give me the code. Thanks in advance.

This is only for field 3 as per your requirement.

awk -F, '!$3{$3=a}{a=$3}1' OFS=, infile

If Solaris, use nawk

--ahamed

2 Likes

It works exactly the way I want. Thanks a lot.

$
$
$ cat f29
MessageFlow,1,BusIntBatchMgr,a
OOBEvent,1,BusIntBatchMgr,a
TaskEvents,1,,a
MTTrace,1,,a
MTWarning,,1,a
MessageFlow,1,Batch,a
OOBEvent,1,Batch,a
TaskEvents,1,,a
EAISAPIdocWizard,1,BusIntMgr,a
EAISAPBAPIWizard,1,BusIntMgr,a
EAISiebelWizard,1,BusIntMgr,a
$
$
$ perl -F, -plane '$F[2] eq "" ?{$F[2]=$x}:{$x=$F[2]}; $_=join(",",@F)' f29
MessageFlow,1,BusIntBatchMgr,a
OOBEvent,1,BusIntBatchMgr,a
TaskEvents,1,BusIntBatchMgr,a
MTTrace,1,BusIntBatchMgr,a
MTWarning,,1,a
MessageFlow,1,Batch,a
OOBEvent,1,Batch,a
TaskEvents,1,Batch,a
EAISAPIdocWizard,1,BusIntMgr,a
EAISAPBAPIWizard,1,BusIntMgr,a
EAISiebelWizard,1,BusIntMgr,a
$
$

tyler_durden