Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit a property value in a property file from shell script

Tags:

bash

shell

sed

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 ?

like image 537
Michael Avatar asked Dec 22 '11 16:12

Michael


2 Answers

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.

like image 177
jaypal singh Avatar answered Nov 11 '22 16:11

jaypal singh


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.

like image 26
Dan Fego Avatar answered Nov 11 '22 16:11

Dan Fego