Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed in a makefile; how to escape variables?

Tags:

makefile

sed

I am writing a generic makefile to build static libraries. It seems to work well so far, except for the line calling sed:

# Generic makefile to build a static library
ARCH       = linux

CFLAGS     = -O3 -Wall

SOURCES    = src
BUILD_DIR  = build/$(ARCH)
TARGET     = $(BUILD_DIR)/libz.a

CFILES     = $(foreach dir,$(SOURCES),$(wildcard $(dir)/*.c))
OBJECTS    = $(addprefix $(BUILD_DIR)/,$(CFILES:.c=.o))

# Pull in the dependencies if they exist
# http://scottmcpeak.com/autodepend/autodepend.html
-include $(OBJECTS:.o=.dep)

default: create-dirs $(TARGET)

$(TARGET): $(OBJECTS)
    $(AR) -rc $(TARGET) $^

$(BUILD_DIR)/%.o: %.c 
    $(CC) $(CFLAGS) -c $< -o $@ 
    $(CC) -M $(CFLAGS) $*.c > $(BUILD_DIR)/$*.tmp
    sed s/.*:/$(BUILD_DIR)\\/$*.o:/ $(BUILD_DIR)/$*.tmp > $(BUILD_DIR)/$*.dep
    @rm $(BUILD_DIR)/$*.tmp

.PHONY: create-dirs
create-dirs:
    @for p in $(SOURCES); do mkdir -p $(BUILD_DIR)/$$p; done

.PHONY: clean
clean:
    rm -fr $(BUILD_DIR)

sed is used to replace the path/name of the object file with the full path of where the object actually is. e.g. 'src/foo.o:' is replaced with 'build/linux/src/foo.o:' in this example. $(BUILD_DIR) and $* in the replacement string both contain forward slashes when expanded - how do I pass them to sed?

Note: This might have been answered here before, but I am so far unable to apply those answers to my specific problem!

like image 280
x-x Avatar asked Jul 08 '10 06:07

x-x


People also ask

How do you escape characters in sed?

Put a backslash before $. */[\]^ and only those characters (but not inside bracket expressions).

How do you replace a variable in a file using sed?

For replacing a variable value using sed, we first need to understand how sed works and how we can replace a simple string in any file using sed. In this syntax, you just need to provide the string you want to replace at the old string and then the new string in the inverted commas.

Can you use sed on a variable?

The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.

How do you use slash in sed?

When in doubt, echo the command: echo sed "s/\//\\\//g" -> sed s/\//\\//g . Btw you can use something else for sed, like 's@/@\\/@g' .


1 Answers

  • You can use anything else than forward slashes as separator in sed. E.g. sed s~foo~bar~g
  • You can use double quotes " (at least in the shell), and variables will still be expanded: echo "Hello $PLANET"
like image 180
Sjoerd Avatar answered Sep 27 '22 22:09

Sjoerd