vikas ramnani
vikas ramnani

Reputation: 155

Changing a value in a file using awk

I have one properties file of the follwoing format (Say name of the file is oldProperties.properties)

group1.value1=Hello
group1.value2=World
group1.value3=BlaBla
group1.vlaue4=blabla2

Now I want to develop a script which changes a particular value in the properties file and create a new file. The script should take propertyName and newValue of the property as command line arguments.

changePropertyValue.ksh group1.value3 GoodBye

The result file (say newProperties.properties) should look like this

    group1.value1=Hello
    group1.value2=World
    group1.value3=GoodBye
    group1.vlaue4=blabla2

For doing this I have written these line of codes in changePropertyValue.ksh

property_name=$1
new_value=$2

old_properties=oldProperties.properties
new_properties=newProperties.properties

echo "" > $new_properties

cat $old_properties |  awk 'BEGIN{ FS="=";OFS="=" } {if($1=="$property_name") $2="$new_value"; print $0;}' >> $new_properties

I am launching this

changePropertyValue.ksh group1.value3 GoodBye 

and now when I do grep on newProperties file I am getting old value i.e

grep group1.value3 newProperties.properties
output 
group1.value3=BlaBla

At the same time if I launch the awk command directly on command line its working fine i.e if I launch this

cat oldProperties.properties |  awk 'BEGIN{ FS="=";OFS="=" } {if($1=="group1.value3") $2="GoodBye"; print $0;}' | grep group1.value3

output is :-
group1.value3=GoodBye

Can anybody please tell me what I am doing wrong while writing the script.

Thanks

Upvotes: 1

Views: 2293

Answers (2)

chepner
chepner

Reputation: 531708

Another alternative is to pass the value of $property_name as a variable to awk:

awk 'BEGIN{ FS="=";OFS="=" } {if($1==pname) $2=newval; print $0;}' pname="$property_name" newval="$new_value" $old_properties >> $new_properties

Upvotes: 2

twalberg
twalberg

Reputation: 62429

The single quotes around the awk program (awk 'BEGIN...') prevent the expansion of $property_name. Change your awk invocation to this:

cat $old_properties |  awk "BEGIN{ FS=\"=\";OFS=\"=\" } {if(\$1==\"$property_name\") \$2=\"$new_value\"; print \$0;}" >> $new_properties

Note that the outer single quotes have been replaced with double quotes, and all the original double quotes have been escaped with \.

Upvotes: 3

Related Questions