views:

110

answers:

2

Hi

I have a properties file, which, when unmodified has the following line:

worker.list=

I would like to use sed to append to that line a value so that after sed has run, the line in the file reads:

worker.list=test

But, when I run the script a second time, I want sed to pick up that a value has already been added, and thus adds a separator:

worker.list=test,test

That's the bit that stumps me (frankly sed scares me with its power, but that's my problem!)

Rich

+2  A: 

Thats easy! If you're running GNU sed, you can write it rather short

 sed -e '/worker.list=/{s/$/,myValue/;s/=,/=/}'

That'll add ',myValue' to the line, and then remove the comma (if any) after the equal sign.

If you're stuck on some other platform you need to break it apart like so

sed -e '/worker.list=/{' -e 's/$/,myValue/' -e 's/=,/=/' -e '}'

It's a pretty stupid script in that it doesn't know about existance of values etc (I suppose you CAN do a more elaborate parsing, but why should you?), but I guess that's the beauty of it. Oh and it'll destroy a line like this

worker.list=,myval

which will turn into

worker.list=myval,test

If that's a problem let me know, and I'll fix that for you.

HTH.

roe
@roe: I have a question since I'm also learning sed: why don't you need a closing `/` at the end of your first sed expression `sed -e '/worker.list=/{s/$/,myValue/;s/=,/=/}'`, before the last `'`?
Alberto Zaccagni
Thanks - it's clear now I've seen it! I had no idea you could chain the operations like that. Good to know.
Rich
@Alberto; there is a closing `/` at the end of it? Note that the first part `/worker.list=/` is a selector, then you have `s/$/,myvalue/` which has a all the slashes it needs, and so does `s/=,/=/`. which closing `/` are you looking for?
roe
@roe: oops, selector! Ok, I thought that the `sed ///` schema was the same for all the cases, I'll have a deeper look at selectors, thank you :)
Alberto Zaccagni
A: 

you can also use awk. Set field delimiter to "=". then what you want to append is always field number 2. example

$ more file
worker.list=
$ awk -F"=" '/worker\.list/{$2=($2=="")? $2="test" : $2",test"}1' OFS="=" file
worker.list=test
$ awk -F"=" '/worker\.list/{$2=($2=="")? $2="test" : $2",test"}1' OFS="=" file >temp
$ mv temp file
$ awk -F"=" '/worker\.list/{$2=($2=="")? $2="test1" : $2",test1"}1' OFS="=" file
worker.list=test,test1

or the equivalent of the sed answer

$ awk -F"=" '/worker\.list/{$2=",test1";sub("=,","=")}1' OFS="=" file
ghostdog74