How to append portion of a file content to another file when a certain pattern is matching?

Please provide both the files and at-least provide 2-3 lines. and desired output also.

text1.txt

XXX XXX XXXX:1234,1111_111,ABCD 123456,XXXX XXXXXX:12345,XX,YYYYY1,ZZZZZ1,
XXX XXX XXXX:1234,1111_111,BCDF 123456,XXXX XXXXXX:12345,XX,YYYYY2,ZZZZZ2,
XXX XXX XXXX:1234,1111_111,CDEF 123456,XXXX XXXXXX:12345,XX,YYYYY3,ZZZZZ3,

text2.txt

ABCD 123456,1111,11111,111111,XX,AAAAAA1,BBBBBB1
CDEF 123456,1111,11111,111111,XX,AAAAAA2,BBBBBB2
BCDF 123456,1111,11111,111111,XX,AAAAAA3,BBBBBB3

Output:

XXX XXX XXXX:1234,1111_111,ABCD 123456,XXXX XXXXXX:12345,XX,YYYYY1,ZZZZZ1,
XXX XXX XXXX:1234,1111_111,BCDF 123456,XXXX XXXXXX:12345,XX,YYYYY2,ZZZZZ2,
XXX XXX XXXX:1234,1111_111,CDEF 123456,XXXX XXXXXX:12345,XX,YYYYY3,ZZZZZ3,

This is the original text file input and it gave the desired output. However with the NewTextFile.txt input below the output is somehow "incorrect" with the same text2.txt.

NewTextFile.txt:

XXXXX XXXXX:123E,1234567_123,ABCD 123456,XXXX XXXX:123E,X,YYYYY1,ZZZZZ1,
XXXXX XXXXX:213E,2345678_123,BCDF 123456,XXXX XXXX:123E,X,YYYYY2,ZZZZZ2,
XXXXX XXXXX:321E,3456789_123,CDEF 123456,XXXX XXXX:123E,X,YYYYY3,ZZZZZ3,

text2.txt

ABCD 123456,1111,11111,111111,XX,AAAAAA1,BBBBBB1
CDEF 123456,1111,11111,111111,XX,AAAAAA2,BBBBBB2
BCDF 123456,1111,11111,111111,XX,AAAAAA3,BBBBBB3

Output:
,XXXX XXXXX:123E,1234567_123,ABCD 123456,XXXX XXX:123E,X,YYYYY1,ZZZZZ1,
,XXXX XXXXX:213E,2345678_123,CDEF 123456,XXXX XXX:123E,X,YYYYY2,ZZZZZ2,
,XXXX XXXXX:321E,3456789_123,BCDF 123456,XXXX XXX:123E,X,YYYYY3,ZZZZZ3,

With the NewTextFile.txt, the first character X is removed and replaced with , (comma) for all new line.

Thank you :slight_smile:

try

awk -F, 'NR==FNR{A[$1]=$NF;B[$NF]=$(NF-1);C[$NF]=$(NF-2);next}{$(NF-1)=A[$3];$(NF-2)=B[$(NF-1)];$(NF-3)=C[$(NF-1)]}1' OFS="," file2 file1

Hi pamu, the output remains the same. With the first X being replaced by a comma.

Another question, awk give me this message when the input file don't have the similar pattern. is there anyway for it to do it in a more "gracious" way ?

In my latest code I have not used substitute function. so there is no chance of X being replaced by ,

Please show us what you tried.

It is very difficult to program any script when you are not aware of it's all in and out.
Yes it can be done but only way is programmer should know all possible scenarios.

Regards,

pamu

Thanks pamu for your help :smiley:

Actually there is no problem with your code. Just formatting of the input file giving me the error :smiley: