This should do:
awk 'FNR==NR {split($0,a,",");b[a[2]]=a[1];next} {n=split($0,d,/[^[:space:]]*/);if(b[$4])$4=b[$4];for(i=1;i<=n;i++) printf("%s%s",d[i],$i);print ""}' fileB fileA
Stores spaces in an array, so it can reuse it later
Example:
cat fileA
xxx xxx xxx Z0002 not change this
xxx xxx Z0002 zzz
xxx Z000223213 xxx Z0002 xxx xxx xxx Z0002
cat fileB
3100,3000
W0002,Z0002
awk 'FNR==NR {split($0,a,",");b[a[2]]=a[1];next} {n=split($0,d,/[^[:space:]]*/);if(b[$4])$4=b[$4];for(i=1;i<=n;i++) printf("%s%s",d[i],$i);print ""}' fileB fileA
xxx xxx xxx W0002 not change this
xxx xxx Z0002 zzz
xxx Z000223213 xxx W0002 xxx xxx xxx Z0002
Some more readable and how it works:
awk '
FNR==NR {
split($0,a,",")
b[a[2]]=a[1]
next
}
{
n=split($0,d,/[^[:space:]]*/)
if(b[$4])
$4=b[$4]
for(i=1;i<=n;i++)
printf("%s%s",d[i],$i)
print ""
}
' fileB fileA
Jotne source
share