Reputation: 191
I want to replace my default make target using sed in a shellscript. First I am trying to get sed to work from command line.
My makefile contains:
all:
gcc -Wall -o main main.c
I want it to contain:
all:
gcc -Wall -o TEST main.c
The sed command I use:
sed -i 's/(-o[ ][^ ]+)/-o TEST/g' Makefile
It seems to work on https://regexr.com/ but when I run the command in ubuntu it does not edit my Makefile. What could be the reason?
Also is main the default make target, or is main.c the default make target? Some terminology things I don't quite understand yet.
Upvotes: 2
Views: 527
Reputation: 189417
The proper soulution is to parametrize the Makefile.
MAIN := main
all:
gcc -Wall -o $(MAIN) main.c
Now you can say make MAIN=TEST
(or make MAIN=fnord
or what have you) without modifying anything.
Modifying code is nearly always the wrong solution (whereas generating code can be a powerful and versatile technique).
Upvotes: 1
Reputation: 626870
You are using the BRE (not ERE) POSIX flavor, so the unescaped (
and )
in your pattern match literal parentheses and +
is also parsed as a literal plus symbol. To create a capturing group in a BRE POSIX pattern, you need to use escaped parentheses. Anyways, the parentheses are redundant in the current regex pattern since you are not using placeholders in the replacement pattern. In GNU sed, you may still use +
in BRE patterns as a 1+ occurrences quantifier, but you need to escape it.
Use
sed -i 's/-o [^ ]\+/-o TEST/g' Makefile
Or
sed -i 's/-o [^ ][^ ]*/-o TEST/g' Makefile
to fix the issue. See the online demo.
Note that \+
quantifier is not recognized by all sed
versions, thus, [^ ][^ ]*
(a non-space followed with 0+ non-spaces) workaround might turn out useful.
Upvotes: 0