How to replace a text in a file conditionally?

I have got about 100 ascii files and I want replace some variable with a new one on an HP-UX system. But I want to put a line of comments before the change. I want to make file1 to file2. I am explaining below.
file1:

line1
line2
export QNAME=ABC
line4
line5

file2:

line1
line2
# the below line is changes on 09/21
#export QNAME=ABC
export QNAME=XYZ
line4
line5

The line export QNAME is not always like export QNAME. But it will have the string ABC. Basically the catch is ABC will be replaced with XYZ - everything else remains same.

Can someone tell me a nice way of doing that ? Thank you very much.

$ echo $STR1
QNAME
$ echo $STR2
ABC
$ echo $STR3
XYZ
$ echo $COMMT
# the below line is changes on 09/21


$ awk '/^export/ && $0 ~ x1"="x2{print x4;print "#"$0;$0="export "x1"="x3;}1' x1=$STR1 x2=$STR2 x3=$STR3 x4="$COMMT" file
line1
line2
# the below line is changes on 09/21
#export QNAME=ABC
export QNAME=XYZ
line4
line5

Guru.

Thanks Guru. Just a small clarification - the line may not have starting string export. It can have the STR1 anywhere in the line and the line will be rewritten replacing the string STR1 with STR2 - that's all. In that case, what should be the awk statement ?

sed '/ABC/ {
h
s/^/#/p
x
s/ABC/XYZ/g
}' INPUTFILE
1 Like