wdk
wdk

Reputation: 373

How to add a value to a comma separated list with sed

Sample input:

common.loader= a # test
commonXloader=a
 common.loader=a
common.loader= a, b
# common.loader=a       
common.loader =
common.loader =#
common.loader = # test

Epected:

common.loader= <everything before # and newline and comma if there is some value> <argument which i want to insert> <everything after hash and newline>

So:

common.loader= a, x # test
commonXloader=a
 common.loader=a, x
common.loader= a, b, x
# common.loader=a       
common.loader = x
common.loader = x# 
common.loader = x # test

I tried but did not get it working with sed. Closest I got was:

sed -r -e 's:((^\s*common\.loader\s*=)(([^#\S]*)(#.*)?))$:\1 x \3:'

Upvotes: 0

Views: 234

Answers (1)

smathy
smathy

Reputation: 27961

You can't really do the conditional comma (conditional upon there being an existing term), the simplest is to do two substitutions first for just adding the comma, and second for replacing =, with =:

sed -re '/^\s*common\.loader\s*=\s*/ {s/(\s*(#|$))/, x\1/; s/=,/=/}'

Note that we do these substitutions only on the right lines using sed's pattern address functionality.

Upvotes: 1

Related Questions