19

I'd like a simple one liner with sed to update a java property value. Without knowing what the current setting of the java property is, and it may be empty)

before

example.java.property=previoussetting

after

example.java.property=desiredsetting
Nitesh
  • 2,286
  • 2
  • 43
  • 65
RandomUser
  • 4,140
  • 17
  • 58
  • 94

2 Answers2

29

This will update your file:

sed -i "/property.name=/ s/=.*/=newValue/" yourFile.properties

This will print into a new file

sed "/property.name=/ s/=.*/=newValue/" yourFile.properties > newFile.properties

This is how you update multiple properties

sed -i -e "/property.name.1=/ s/=.*/=newValue1/" -e "/property.name.2=/ s/=.*/=newValue2/" yourFile.properties

Gurus of sed may blame me since this is not the most proper way to do this (e.g. I didn't escape the dots) but I see this as the best option when you don't want to sacrifice readability.

Here's extended discussion: How do I use sed to change my configuration files, with flexible keys and values?

Community
  • 1
  • 1
DenisS
  • 1,637
  • 19
  • 15
22

Assuming Linux Gnu sed, 1 solution would be

Edits escaped '.' chars i.e. s/example\.java.../ per correct comment by Kent

 replaceString=desiredsetting
 sed -i "s/\(example\.java\.property=\).*\$/\1${replaceString}/" java.properties

If you're using BSD sed on a Mac for instance, you'll need to supply an argument to the -i to indicate the backup filename. Fortunately, you can use

 sed -i '' "s/\(example\.java\.property=\).*\$/\1${replaceString}/" java.properties  

as an argument, and avoid having to manage .bak files in your workflow. (BSD sed info added 2018-08-10)

If your sed doesn't honor the -i, then you have to manage tmp files, i.e.

    sed "s/\(example\.java\.property=\).*\$/\1${replaceString}/" java.properties > myTmp
    /bin/mv -f myTmp java.properties

I hope this helps.

Wayne Hartman
  • 18,369
  • 7
  • 84
  • 116
shellter
  • 36,525
  • 7
  • 83
  • 90
  • -1 although OP has accepted this answer. the 'dot' is not escaped, so it means 'ANY character' it could change the wrong property in the file. it's dangerous! – Kent Feb 20 '12 at 21:23
  • @Kent : Dangerous seems like a strong term. But thanks for helping make my post better. Hoofamon : please see revised post for improve replacements on your java properties. Good luck to all. – shellter Feb 20 '12 at 21:43