Reputation: 33
I have this code
BEGIN { FS=OFS=";" }
{ key = $(NF-1) }
NR == FNR {
for (i=1; i<(NF-1); i++) {
if ( !seen[key,$i]++ ) {
map[key] = (key in map ? map[key] OFS : "") $i
}
}
next
}
{ print $0 map[key] }
I use code in this way
awk -f tst.awk 2.txt 1.txt
I have two text files
1.txt
AA;BB;
2.txt
CC;DD;BB;AA;
I try to generate this 3.txt output
AA;BB;CC;DD;
but with this script is not possible because this script return only AA;BB;
logic: The above just uses literal strings in a hash lookup of array indices so it doesn't care what characters you have in your input. However about sample output:
if in 2.txt there are common fields also in 1.txt.for example BB;AA;
then you need concatenate them in a single row, i.e AA;BB;CC;DD;
Ordering is not required, for example is not relevant if output is BB;AA;DD;CC;
Only condition that is required is avoid duplicates but my script already does this
Upvotes: 1
Views: 147
Reputation: 133680
Could you please try following, as per OP's comment both files have only 1 line. So using paste
command to combine both the files and then processing its output by awk
command.
paste -d';' 1.txt 2.txt |
awk '
BEGIN{
FS=OFS=";"
}
{
for(i=1;i<=NF;i++){
if(!seen[$i]++){ val=(val?val OFS:"")$i }
}
print val
delete seen
val=""
}'
Upvotes: 1