-1

I'm trying to do something like:

wt=$(sed -n ... file1) 
sed -i "s/temp/$(wt)/" file2

wt is a variable which is getting it's value from file1 and I want to replace "temp" in file2 wth the value of wt.

The sed commands work as I tried to do the same thing in terminal and it works, but when I run "make", it's giving output as:

wt=
sed -i "s/temp//" file2

I'm using GNU Make 4.3.

Edit: I'm trying to do this in a function in my Makefile, like this:

define func
    wt=$(sed -n ... $(2)) 
    sed -i "s/temp/$(wt)/" $(1)
endef
metal_dent
  • 51
  • 2
  • 5
  • maybe because you need `$$` instead of `$` in a makefile? see https://stackoverflow.com/questions/26564825/what-is-the-meaning-of-a-double-dollar-sign-in-bash-makefile and https://stackoverflow.com/questions/19625368/write-dollar-sign-in-sed-command-pattern-inside-makefile – Sundeep May 14 '20 at 07:05
  • tried adding $ to both the places but that also didn't work – metal_dent May 14 '20 at 07:18
  • not sure then, but perhaps because you are using `$(wt)` instead of `${wt}` ? – Sundeep May 14 '20 at 07:42
  • @Sundeep this time the output is:` wt=$(sed -n ... file1) sed -i "s/temp/${wt}/" file2 ` – metal_dent May 14 '20 at 07:46

1 Answers1

0

Do it in the same way as this:

$ cat data.txt 
temp

$ cat Makefile 
define func
wt=$$(echo $(2)); \
sed "s/temp/$$wt/" $(1)
endef

.PHONY: all

all:
    $(call func,data.txt,name)

$ make
wt=$(echo name); sed "s/temp/$wt/" data.txt
name

This will not work:

define func
wt=$$(echo $(2))
sed "s/temp/$$wt/" $(1)
endef

Why? Because if you do that, the recipe:

all:
    $(call func,data.txt,name)

after make expansion becomes:

all:
    wt=$(echo name)
    sed "s/temp/$wt/" data.txt

As you know, each line of a recipe is executed in its own shell.

    wt=$(echo name) # `wt` is a shell variable in this shell
    sed "s/temp/$wt/" data.txt # `wt` is undefined in this shell

So you need the recipe to execute a line:

    wt=$(echo name); sed "s/temp/$wt/" data.txt # Same shell

or with a line-continuation:

wt=$$(echo $(2)); \
sed "s/temp/$$wt/" $(1)

Equally, you could write:

define func
wt=$$(echo $(2)); sed "s/temp/$$wt/" $(1)
endef
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182