I think this would best be done with AWK, but not sure. Its been stumping me all day how to do this. I have a text file with * delimiters between the fields on the lines. I need to search for lines beginning with L11*1Z and save the value to a variable or buffer starting with 1Z up to but not including the next * (ie the 2nd field on the line), in the first case this would be 1ZXDF430. Then I need to go to the next line that begins with BGN and replace the string QVD (ie the 3rd field on that line) with the value of the variable. I need to do this for all L11*1Z and following BGN lines found in the file. It would be good to output a new file as a result, if possible rather than overlay the input file.
Input file
xxx
L11*123456*CR
yyy
L11*1ZXDF430*2I*04
zzz
BGN*00*QVD*123456
fff
L11*768907*CR
L11*12345678*CR
xxx
L11*1ZXDF499*2I*04
zzz
BGN*00*QVD*123456
xxx
Resulting output file
xxx
L11*123456*CR
yyy
L11*1ZXDF430*2I*04
zzz
BGN*00*1ZXDF430*123456
fff
L11*768907*CR
L11*12345678*CR
xxx
L11*1ZXDF499*2I*04
zzz
BGN*00*1ZXDF499*123456
xxx