I've seen a number of posts about injecting single lines at the beginning of a file. However, I haven't really any that answer to injecting a block of text into the beginning of an existing file. While I have a solution:
install -bDm 0660 -o root -g root <(
echo "# Set external URL"
printf "external_url = '%s'\n\n" "${EXTERNAL_URL}"
cat <PATH_TO_EXISTING_FILE>
) <PATH_TO_EXISTING_FILE>
This feels really ugly. So, I was wondering if there was something less kludgey (and that didn't rely on encapsulating python/perl/etc. within a bash script).
Note: I had ultimately settled on this method because when you try something more like:
(
echo "# Set external URL"
printf "external_url = '%s'\n\n" "${EXTERNAL_URL}"
cat <PATH_TO_EXISTING_FILE>
) <PATH_TO_EXISTING_FILE>
You get an error like cat: <PATH_TO_EXISTING_FILE>: input file is output file.
I would solve this with an in-place sed command:
sed -i -e "1i # Set external URL\nexternal_url = '${EXTERNAL_URL}'\n\n" <PATH_TO_EXISTING_FILE>
Explanation:
-i means edit the file in place-e to provide the expression on the command line1i <contents> says insert <contents> at the first line\n gets replaced by a newline by sed itself, not the shell, so this should work in any shell.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With