Error passing parameter in "sub" command in awk

I have to replace the pattern found in one file in another file with null/empty "" if found on the fields 3 or 4 ONLY

File 1
====
10604747|Mxdef|9999|9999|9999|2012-03-04 00:00:59
10604747|Mcdef|8888|9999|8888|2012-03-04 00:00:59
.
.
.
File 2
====
9999
8888
.
.
.
 
Expected output:
 
File 1
====
10604747|Mxdef|||9999|2012-03-04 00:00:59
10604747|Mcdef|||8888|2012-03-04 00:00:59

I tried something like

while read i
do
awk -v FS="|" -v OFS="|" 'BEGIN { split("3|4", F); } { for(N in F) sub(/'$i'/, "", $(F[N])) } 1' File1 > File1_tp
mv File1_tp File1
done < File2

This is not working. I am getting error in the awk statement inside the while loop. The parameter passing is not working fine.:frowning:

Someone, please help on this.:wall:

awk -F"|" -v OFS="|" 'NR==FNR{a[$0];next}$3 in a{$3=""}$4 in a{$4=""}1' file2 file1
1 Like

Try:

awk 'NR==FNR{A[$1];next}$3 in A{$3=x}$4 in A{$4=x}1' file2 FS=\| OFS=\| file1
1 Like

THanks both the codes work. But if number of date fields increases, the code becomes more lengthy...

---------- Post updated at 09:25 PM ---------- Previous update was at 09:24 PM ----------

Can some one please explain one of the code?

---------- Post updated at 10:20 PM ---------- Previous update was at 09:25 PM ----------

How to make the code dynamic so that it can handle multiple fields rather than restricting it to two fields?

You agreed not to bump posts when you registered. Please stop doing it. We are not "on call"; if someone doesn't answer your post immediately, wait!

What exactly do you want? Do you need to give it a list of fields, a range of fields, or what?

---------- Post updated at 11:05 AM ---------- Previous update was at 10:54 AM ----------

For a list of fields separated by |:

awk -v FIELDS="3|4" -v FS="|" -v OFS="|" 'BEGIN { split(FIELDS, F); }
NR==FNR { A[$1]=1; print "skip " $1; next }
{ for(X in F) if(A[$(F[X])]) $(F[X])="" } 1' fields data
10604747|Mxdef|||9999|2012-03-04 00:00:59
10604747|Mcdef|||8888|2012-03-04 00:00:59

$
1 Like

I dint mean to bump the post. That was totally unintentional :slight_smile:

If you edit, that doesn't bump.

oh ok...I was using the "quick reply" it looked like it was editing...but dint realize it was actually bumping the post