0

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  
2

Assuming there's a BGN after each L11*1Z, then you should be able to use

$ awk 'BEGIN{OFS=FS="*"} /^L11\*1Z/ {x = $2} /^BGN/ {$3 = x} 1' 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.