Thursday, February 3, 2022

[SOLVED] Using sed to update a property in a java properties file

Issue

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

Solution

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.



Answered By - shellter
Answer Checked By - Katrina (WPSolving Volunteer)