Monday, October 25, 2021

[SOLVED] Append to current line if previous line pattern matches

Issue

I'm looking for awk/sed command to append character to current line if the previous line has a pattern?

Example:

SELECT customer from Cust_tab WHERE forename = "XXX"                        
sname = "YYY"
postcode="ZZ ZZZ"

Expected:


SELECT customer from Cust_tab WHERE forename = "XXX"   
AND sname = "YYY"                      
AND postcode="ZZ ZZZ"

I want to add AND to beginning of line if previous/first line has =. Tried doing

sed 's/WHERE.*/& AND/g' 

but this adds to end of line and not beginning and unable to repeat it for 3rd line in file


Solution

EDIT: Following code may help you which will set a flag when a line is having string SELECT and till a empty line comes it will keep adding AND string to all lines.

awk '/^SELECT.*=/{print;flag=1;next} !NF{flag=""} flag{print "AND ",$0}' Input_file

Your question is not that clear but based on your statements and shown samples could you please try following and let me know if this helps.

awk '/=/{print;getline;print "AND " $0}' Input_file


Answered By - RavinderSingh13