Michael
Michael

Reputation: 22957

Edit a property value in a property file from shell script

The title says all. i need to replace a property value whom i don't know to a different value. i'm trying this:

#!/bin/bash
sed -i "s/myprop=[^ ]*/myprop=$newvalue/g" file.properties

i get sed: -e expression #1, char 19: unknown option tos'`

I think the problem is that $newvalue is a string that represents a directory so it messes up sed.

What can I do ?

Upvotes: 12

Views: 31313

Answers (3)

jaypal singh
jaypal singh

Reputation: 77145

If your property file is delimited with = sign like this -

param1=value1
param2=value2
param3=value3

then you can use awk do modifiy the param value by just knowing the param name. For example, if we want to modify the param2 in your property file, we can do the following -

awk -F"=" '/^param2/{$2="new value";print;next}1' filename > newfile

Now, the above one-liner requires you to hard code the new value of param. This might not be the case if you are using it in a shell script and need to get the new value from a variable.

In that case, you can do the following -

awk -F"=" -v newval="$var" '/^param2/{$2=newval;print;next}1' filename > newfile

In this we create an awk variable newval and initialize it with your script variable ($var) which contains the new parameter value.

Upvotes: 10

Michael Hegner
Michael Hegner

Reputation: 5823

I found a function from someone named Kongchen. He wrote a function script to change property values and it worked fine for me:

Check it out: https://gist.github.com/kongchen/6748525

Upvotes: 3

Dan Fego
Dan Fego

Reputation: 14014

sed can use characters other than / as the delimiter, even though / is the most common. When dealing with things like pathnames, it's often helpful to use something like pipe (|) instead.

Upvotes: 7

Related Questions