Search code examples
sedappendeol

sed conditionally + append to end of line if condition applied


Playing with makefile and bash shell scripting where I ended-up having a variable containing:

--global-option=build_ext --global-option=--b2-args=libtorrent-python-pic=on --global-option=--b2-args=address-model=32

I need to convert it so double-quotes gets appended at the right place such as:

--global-option=build_ext --global-option=--b2-args="libtorrent-python-pic=on"  --global-option=--b2-args="address-model=32"

I tried the following without success:

echo $myvar | sed -e 's/ /\n/' | sed -z '{s/=/="/2;t;s/$/"/}'
--global-option=build_ext
--global-option="--b2-args=libtorrent-python-pic=on

EDIT: Note that this time it's --b2-args= but this could be a conjunction of --anything=, and the reason why I was focussing on the second instance of = to change for =" and if true append = at the end of word.


Solution

  • Since your question doesn't discuss anything about prepending --global-option= if it's missing as in the final --b2-args... string on the provided input line, I think your input was really supposed to be:

    $ cat file
    --global-option=build_ext --global-option=--b2-args=libtorrent-python-pic=on --global-option=--b2-args=address-model=32
    

    in which case using any sed in any shell on every Unix box:

    $ sed 's/\([^ =]*=[^= ]*=\)\([^ ]*\)/\1"\2"/g' file
    --global-option=build_ext --global-option=--b2-args="libtorrent-python-pic=on" --global-option=--b2-args="address-model=32"