简体   繁体   中英

Prepend a text to a file in Makefile

I am trying to pre-pend a text to a file using a Makefile. The following bash command works in terminal:

echo -e "DATA-Line-1\n$(cat input)" > input

But when I put the above command in a Makefile, it does not work:

copyHeader:
    @echo -e "DO NOT EDIT THIS FILE \n$(cat input)" > input

I guess $(cat input) does not work as expected in the Makefile.

I'd recommend sed for prepending a line of text to a file. The i command is kind of a pain; some clever use of the hold space does the same thing in a more complicated but less troublesome way:

copyHeader:
    sed -i "" '1{h;s/.*/NEW FIRST LINE/;G;}' input

But if you want to do it your way, I think an extra '$' will do the trick:

\n

copyHeader:
@echo -e "DO NOT EDIT THIS FILE \\n$$(cat input)" > input

EDIT: Thanks to MadScientist for pointing out that this method (using $(cat input) ) is unreliable.

A file function was added to make in 4.0, which as of 4.2 can also read from files

The newline is a little bit hacky but this can be accomplished with make alone:

define n


endef

copyHeader:
    $(file > input,DATA-Line-1$n$(file < input))

After messing around with this for a while (accepted answer does not work with the sed that comes with OSX 10.12, make was too old for the file manipulation options), I settled on the following (ugly) solution:

echo "DATA-Line-1" > line.tmp
mv input input.tmp
cat line.tmp input.tmp > input
rm input.tmp line.tmp

This works for me:

$ cat test
this
is
a
test

$ sed -i "1i new first line" test

$ cat test
new first line
this
is
a
test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM