How to insert text before the first line of a file?

I’ve been looking around sed command to add text into a file in a specific line.
This works adding text after line 1:

sed '1 a

But I want to add it before line 1. It would be:

sed '0 a

but I get this error: invalid usage of line address 0.

Any suggestion?

Asked By: Manolo

||

Use sed‘s insert (i) option which will insert the text in the preceding line.

sed '1 i

Question author’s update:

To make it edit the file in place – with GNU sed – I had to add the
-i option:

sed -i '1 ianything' file

Also syntax

sed  -i '1i text' filename

For non-GNU sed

You need to hit the return key immediately after the backslash 1i and after first_line_text:

sed -i '1i
first_line_text
'

Also note that some non-GNU sed implementations (for example the one on macOS) require an argument for the -i flag (use -i '' to get the same effect as with GNU sed).

For sed implementations that does not support -i at all, run without this option but redirect the output to a new file. Then replace the old file with the newly created file.

Answered By: suspectus

You want to insert text before the first line rather than append it after, so use

sed '1 i
your_text' your_file

A here document can also help:

cat /dev/stdin your_file <<EOI
Your text
goes here
EOI
Answered By: Joseph R.
sed  -i '1i new_text' file_name

If you don’t specify the -i option, it won’t show any error, and displays the output on standard terminal, but doesn’t insert the text in the file.

Answered By: devi.

You can use the POSIX tool ex:

ex a.txt <<eof
1 insert
Sunday
.
xit
eof

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html

Answered By: Zombo

Using GNU awk >= 4.1:

awk -i inplace 'BEGINFILE{print "first line"}{print}' foo.sh

In opposite to all the sed answers, this works on empty files too.

Answered By: rudimeier

The 0a command you attempted does work in ex, the predecessor to vi:

printf '%sn' 0a 'Anything you want to add' . x | ex file.txt

The printf command by itself outputs:

0a
Anything you want to add
.
x

The 0a means append after the 0th line (i.e. before the first line).

The next line or multiple lines is literal text to be added.

The . on a line by itself terminates the “append” command.

The x causes Ex to save the changes to the file and exit.

Answered By: Wildcard

Echo is used to get the text. Cat filename – prints the file in the console and > uses it to send to another file filename1 and then we move filename1 to filename to get the text inserted to the first line of desired file.

  (echo "some text" && cat filename) > filename1 && mv filename1 filename
Answered By: Ankit Shah

I am surprised that in this old question nobody has shown the most common (and quite simple in this case) sed command:

$ sed  -i '1s/^/new_text
/' file_name

Which works in most shells and is portable to several sed versions, provided that the file contains at least one valid line.
If GNU sed is available, you may use this:

$ sed -i '1s/^/new_textn' file_name

The difference is that GNU sed allow the use of a n for a newline and others need a literal newline preceded by a backslash (which also work in GNU sed anyway).

If a shell which accepts the $'…' syntax is in use, you may insert the newline directly, so sed sees that the newline is already there:

$ sed -i $'1s/^/new_text\n/' file_name

Which works for more sed versions.

If the file has no lines (i.e: its empty) just:

$ echo "new_text" > file_name
Answered By: user232326

Unfortunately, all the answers above (mostly with sed) didn’t work out for me since they all substituted the first line. I am on an Ubuntu 16.04 LTS machine. Here is my workaround with GNU Awk 4.0.2:

awk '{if(NR==1){$0="NEW_FIRST_LINE"$0; print $0} ;if(NR!=1){print $0}}' file_name
Answered By: Splinter479

sed can insert (multiple times) before the first and after the 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
    • Script 4 applies only to “line <last>” because of the $ placed before the s/.

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        ",
    "                      "
  ]
}
Answered By: Bruno Bronosky

If anyone is interested, my problem was to insert same header line into several files. Thanks to proposed solution, I came up with this :

sed -i 1i $(cat header_line) data.csv

where header_line is a file containing desired first line ,

Answered By: rookie

Adding the text hello before the first line without a carriage return or line feed to the file myfile

sed -i '1s/^/hello /' myfile

This will also not output the entire file on the terminal.

Answered By: FastGTR

I had issues with BSD sed (MacOS) and inserting text from a variable, so this is how I did it:

headers=a,b,c
sed -i '' -e "1{x;s/^.*/$headers/p;x;} some_file"

Explanation

  • 1{...} This affects only the first line
  • x swap the current line with the hold space (currently empty)
  • s/../../p replaces (the now empty line) with the expected text (this avoids the line-break problem) and outputs it (so the first line will be get printed)
  • x swap again, retrieving the file first line which was in the hold space into the pattern space
Answered By: estani

Just similar to Ankit Shah’s answer:

(echo "some text" && cat filename) > /tmp/filename && cat /tmp/filename > filename

It’s not convenient to use such a long command, so I create a simple bash function (in .bashrc or elsewhere possible) as following:

echo0 () {
  (echo ${@:2} && cat $1) > /tmp/$1
  cat /tmp/$1 > $1
}
# $1 is your-file-name, ${@:2} are contents after "your-file-name".
# How to use:
#   > echo0 myfile hellow world etc.
#   > head myfile
#     hellow world etc.
#     ...
Answered By: Hao Liu

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
Answered By: Ax_
echo -e "task goes heren$(cat todo.txt)" > todo.txt

echo "task goes here
$(cat todo.txt)" > todo.txt

echo 'task goes here'$'n'"$(cat todo.txt)" > todo.txt

(https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash)

Answered By: user1855805
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.