Well, I spent a couple of hours playing in sed and couldn't find a way - but then I'm not very good with sed!
I did manage to create a solution of sorts with awk.
It uses a csv containing the variable name, 'apply' fieldname, 'type' fieldname, and the replacement field name to use. E.g.:
# cat xf.txt
var,applypol,polmethod,pol.apply
var2,fldapply,fldtype,fld.apply
var4,apply,type,apply
Bash script - creates an awk (actually gawk) program using the csv data, and then calls it:
cat xx.sh
#!/bin/sh
AWKFILE=`basename $0`_$$.awk
[[ -f $AWFILE ]] && rm $AWKFILE
while IFS=',' read VN AN TN RN
do
cat >> $AWKFILE <<EOFILE
/$VN\.$TN *= *'[^']*'/ {
match (\$0, "(.*)$VN.$TN *= *'([^']*)';(.*)",statements);
${VN}_type=statements[2];
if ( ${VN}_apply != "" ) {
if ( ${VN}_apply == "true" ) {
printf ("%s$VN.$RN = '%s'; %s\n", statements[1], ${VN}_type, statements[3]);
}
else {
printf ("%s$VN.$RN = \"; %s\n", statements[1], statements[3]);
}
}
else {
printf ("%s%s\n", statements[1], statements[3]);
}
}
/$VN\.$AN *= *'[^']*'/ {
match (\$0, "(.*)$VN.$AN *= *'([^']*)';(.*)",statements);
${VN}_apply=statements[2];
if ( ${VN}_type != "" ) {
if ( ${VN}_apply == "true") {
printf ("%s$VN.$RN = '%s'; %s\n", statements[1], ${VN}_type, statements[3]);
}
else {
printf ("%s$VN.$RN = \"; %s\n", statements[1], statements[3]);
}
}
else {
printf ("%s%s\n", statements[1], statements[3]);
}
}
EOFILE
if [ -z "$exclstr" ]
then
exclstr="$VN.$AN|$VN.$TN"
else
exclstr=$exclstr"|$VN.$AN|$VN.$TN"
fi
done < $2
cat >> $AWKFILE <<EOFILE
\$0 !~ /($exclstr) *= *'[^']*'/ {
print;
}
EOFILE
gawk -f $AWKFILE $1
rm $AWKFILE
Which seems to work:
# cat xx.txt
% whatever 1
dummy3 = 7; var.polmethod= 'optionA'; dummy4 = 8;
% whatever 2
dummy1 = 5; var.applypol = 'false'; dummy2 = 6;
dummy1 = 5; var2.fldapply = 'false'; dummy2 = 6;
% whatever 3
dummy3 = 7; var2.fldtype= 'option1'; dummy4 = 8;
% whatever 4
dummy3 = 7; var3.fldtype = 'optionB'; dummy4 = 8;
% whatever 5
dummy1 = 5; var3.fldapply = 'true'; dummy2 = 6;
% whatever 6
% whatever 7
% whatever 8
dummy1 = 5; var4.apply = 'true'; dummy2 = 6;
% whatever 9
% whatever 10
% whatever 11
% whatever 12
dummy3 = 7; var4.type ='option2'; dummy4 = 8;
% whatever 13
# ./xx.sh xx.txt xf.txt
% whatever 1
dummy3 = 7; dummy4 = 8;
% whatever 2
dummy1 = 5; var.pol.apply = "; dummy2 = 6;
dummy1 = 5; dummy2 = 6;
% whatever 3
dummy3 = 7; var2.fld.apply = "; dummy4 = 8;
% whatever 4
dummy3 = 7; var3.fldtype = 'optionB'; dummy4 = 8;
% whatever 5
dummy1 = 5; var3.fldapply = 'true'; dummy2 = 6;
% whatever 6
% whatever 7
% whatever 8
dummy1 = 5; dummy2 = 6;
% whatever 9
% whatever 10
% whatever 11
% whatever 12
dummy3 = 7; var4.apply = 'option2'; dummy4 = 8;
% whatever 13
I'm sure there must be an easier way though (and I suspect enough variables to replace will cause something in there to fail horribly).