1

When using mk, GNU sed, I find that variables do not expand at all.

Problematic code:

VAR=qux
...
build:
    sed -i "s|FOO = .*|FOO = $VAR|" bar.file

This seems to run the following:

sed -i "s|FOO = .*|FOO = $VAR|" bar.file

when I want it to run

sed -i "s|FOO = .*|FOO = qux|" bar.file

I have tried using single quotes and double quotes, as other stack exchange posts have mentioned. The only instance I can get $VAR to expand is when there are no quotes around it. Which of course means that sed no longer sees the expression as an expression.

Aster
  • 121
  • 9
  • If this is `bash` then put `set -x` before the `sed` call. That shows you what the shell executes. – Hauke Laging Aug 20 '17 at 08:48
  • 1
    "a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed)" -- This is not the case, the case was the quoting in my original. The quoting is not a form of typo as it was done intentionally. This problem caused me much strife and no help was available anywhere on the internet. This problem *is* reproducible. – Aster Aug 21 '17 at 11:38

2 Answers2

2

This looks like a fragment in a Makefile.

There's two errors in the file:

  1. The sed substitution command uses | as the delimiter, but the middle delimiter is /.

  2. The Makefile variable VAR is dereferenced as $VAR instead of $(VAR) or ${VAR}.

Note that a Makefile is not a shell script. Therefore, the following Makefile is perfectly valid and will produce the string qux world as output on the terminal:

VAR=    qux                                        

build:                                             
        @echo 'hello world' | sed 's|hello|$(VAR)|' 

In a Unix Makefile, $VAR would expand to the value of the variable V followed by the letters AR. This is because unless otherwise stated, variables' names are a single character. If you have multi-character variable names, you must enclose the whole name in either $(...) or ${...}.

Obviously, Plan9 Makefiles may be different in that respect.


UPDATE:

The following mkfile outputs the correct value when using mk 2.0, hello = qux:

VAR=qux

all:
        echo "hello = bar" | sed "s/= bar/= $VAR/"

So the quoting in the question seems correct to me.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
0

It turns out that, while I had previously tried escaping it, I erroneously put double quotes around it like so:

sed -i 's|FOO = .*|FOO = '"$VAR"'|' bar.file

Changing it to

sed -i 's|FOO = .*|FOO = '$VAR'|' bar.file

works.

Aster
  • 121
  • 9