How do I insert text to the 1st line of a file using sed?

Viewed 18671

Hi I'm trying to add text to the 1st line of a file using sed so far iv'e tried

#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test

And this dosn't work also tried

#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test

this dosn't seem to work either oddly when I try

#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test

I get the 1st line of text to appear when i use cat test but as soon as i type sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;" I can't see the information that i sould do on line 2 this being ssl_certificate_key /etc/example/live/example.com/privkey.pem;

so my question to summerise

  1. Can text be inserted into the 1st line of a newly created file using sed?
  2. If yes whats the best way of inserting text after the 1st line of text?
5 Answers

First and Last

I would assume that anyone who searched for how to insert/append text to the beginning/end of a file probably also needs to know how to do the other also.

cal |                            \
  gsed -E                        \
       -e     '1i\{'             \
       -e     '1i\  "lines": ['  \
       -e 's/(.*)/    "\1",/'    \
       -e '$s/,$//'              \
       -e     '$a\  ]'           \
       -e     '$a\}'

Explanation

This is cal output piped to gnu-sed (called gsed on macOS installed via brew.sh) with extended RegEx (-E) and 6 "scripts" applied (-e) and line breaks escaped with \ for readability. Scripts 1 & 2 use 1i\ to "at line 1, insert". Scripts 5 & 6 use $a\ to "at line <last>, append". I vertically aligned the text outputs to make the code represent what is expected in the result. Scripts 3 & 4 do substitutions (the latter applying only to "line <last>"). The result is converting command output to valid JSON.

output

{
  "lines": [
    "    October 2019      ",
    "Su Mo Tu We Th Fr Sa  ",
    "       1  2  3  4  5  ",
    " 6  7  8  9 10 11 12  ",
    "13 14 15 16 17 18 19  ",
    "20 21 22 23 24 25 26  ",
    "27 28 29 30 31        ",
    "                      "
  ]
}

For help getting this to work with the macos/BSD version of sed, see my answer here.

To insert text to the first line and put the rest on a new line using sed on macOS this worked for me

sed -i '' '1 i \
Insert
' ~/Downloads/File-path.txt
Related