Dev
Dev

Reputation: 55

Append to current line if previous line pattern matches

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

Upvotes: 1

Views: 543

Answers (2)

karakfa
karakfa

Reputation: 67567

with awk

$ awk 'e{$0="AND " $0; e=0}1; /=/{e=1}' file

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133760

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

Upvotes: 3

Related Questions