Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert block of text at beginning of a file

Tags:

file

bash

insert

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.

like image 558
Thomas H Jones II Avatar asked Dec 22 '25 06:12

Thomas H Jones II


1 Answers

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 line
  • 1i <contents> says insert <contents> at the first line
  • and \n gets replaced by a newline by sed itself, not the shell, so this should work in any shell.
like image 84
joanis Avatar answered Dec 23 '25 23:12

joanis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!