Sed conditional replace

Given this row:

|lastname1|middlename1|firstname1|lastname2|middlename2|firstname2

produce this result:

|lastname|middlename|firstname

where the resultant names are based on the presence of the #2 names above. I.e., if a #2 name is passed (usually will be null,) use that - otherwise use the #1 counterpart.

Example:

|Smith|Frederick|John|null|null|Johnny

result:

|Smith|Frederick|Johnny

I'm just curious if this is something that can be done conditionally in sed - admittedly more for my curiosity than anything else. I'm geared up to just crank out the modest perl to get this done - but I'm looking for something not so "business as usual." :slight_smile:

Thanks in advance, Al

 
awk -F '|' '{if($4=="null") print $1"|"$2"|"$3; else print $4"|"$5"|"$6;}' inputFile

OR

 
awk -F '|' '{if($4=="null") print $1,$2,$3; else print $4,$5,$6;}' OFS='|' inputFile

for inputFile containing

 
fdfdf|dfdf|ttrtr|null|null|gfg
fsdfd|hghg|ere|qw12|rer|rrer

Result is

 
fdfdf|dfdf|ttrtr
qw12|rer|rrer

Is it what you are looking for?

Is it really "null" or is it just an empty field. If the latter is the case change "null" to "" :

awk -F\| '{for(i=2;i<=4;i++)if($(i+3)!="null")$i=$(i+3);NF-=3}1' OFS=\| infile

Could be done with shell either and notations like

IFS='|' read l1 m1 f1 l2 m2 f2
lastname=${l2:-$l1} 
firstname=${f2:-$f1}
middlename=${m2:-$m1}

With the proper while loop and printf statement yes, if the [lfm]2 values are not literally "null" that is..

@ctsgnb
I always get [lfm]2 even if they are null
@Scrutinizer
I guess loop should execute for i=1 to 3

 
for(i=1;i<=3;i++)

In this case, because of the leading | , $1 is always empty.

Agreed. I didn't notice leading |
looping should be for i=2 to 4
Tks !!

Oh... "null" is a string ! OMG i missed that

LOL :slight_smile: