327

So far I've been able to find out how to add a line at the beginning of a file but that's not exactly what I want. I'll show it with an example:

File content

some text at the beginning

Result

<added text> some text at the beginning

It's similar but I don't want to create any new line with it...

I would like to do this with sed if possible.

1

21 Answers 21

498

sed can operate on an address:

$ sed -i '1s/^/<added text> /' file

What is this magical 1s you see on every answer here? Line addressing!.

Want to add <added text> on the first 10 lines?

$ sed -i '1,10s/^/<added text> /' file

Or you can use Command Grouping:

$ { echo -n '<added text> '; cat file; } >file.new
$ mv file{.new,}
14
  • 122
    To actually insert a new line: sed -i '1s/^/<added text> \n/' file
    – jslatts
    Sep 17, 2013 at 13:27
  • 2
    Why using -i ?? On man it says that it is for suffix. linux.die.net/man/1/sed May 15, 2015 at 2:56
  • 2
    -i stands for in-place, you can append a suffix to -i to make a copy rather than overwrite. -i.new would make a new file ending with .new, but just -i would edit the file directly.
    – Jay Kamat
    May 22, 2015 at 21:31
  • 6
    Note that the sed won't work on an empty file - afaict sed can't be made to do anything at all with 0-length input.
    – jthill
    Oct 5, 2015 at 20:38
  • 4
    The flaw of this solution is that it doesn't add the text if file is empty.
    – DBedrenko
    Apr 16, 2016 at 20:45
86

If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above.

The best solution will add the string, but with the string, it will not add a line at the end of a file.

sed -i '1s/^/your text\n/' file
2
  • On Mac OS, was getting error with "undefined label". Found that you need to give an extension for a backup file; see mkyong.com/mac/…
    – bagsmode
    Aug 10, 2021 at 17:18
  • 10
    Under Mac OS's sed version you have to supply backup file name with -i option. One can pass just an empty string for no backup like sed -i '' '1s/^/new test\n/' filename Feb 4, 2022 at 9:52
32

If the file is only one line, you can use:

sed 's/^/insert this /' oldfile > newfile

If it's more than one line. one of:

sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile

I've included the latter so that you know how to do ranges of lines. Both of these "replace" the start line marker on their affected lines with the text you want to insert. You can also (assuming your sed is modern enough) use:

sed -i 'whatever command you choose' filename

to do in-place editing.

0
27

Use subshell:

echo "$(echo -n 'hello'; cat filename)" > filename

Unfortunately, command substitution will remove newlines at the end of file. So as to keep them one can use:

echo -n "hello" | cat - filename > /tmp/filename.tmp
mv /tmp/filename.tmp filename

Neither grouping nor command substitution is needed.

3
  • 1
    this solution delete empty lines at the end of the file Sep 9, 2020 at 5:34
  • 2
    This is the superior and simpler solution to all the other ones using sed, which don't work for empty files.
    – WalksB
    Nov 12, 2020 at 18:32
  • @dafnahaktana that's because of command substitution
    – Nick Roz
    Nov 13, 2020 at 13:40
18

To insert just a newline:

sed '1i\\'
4
  • 2
    I wonder why the top voted answers all use s instead of i. Any downsides to this?
    – Caesar
    Jul 3, 2020 at 5:04
  • 4
    @Caesar Because when all you have is a hammer, every problem looks like a nail.
    – Tobia
    Jun 21, 2021 at 13:34
  • @Caesar What's the difference between them? Nov 12, 2023 at 0:13
  • 1
    @HashimAziz That's kind of what I'm asking... (i is "unconditional insert", s is "match and replace". And most sed usage is s only, so Tobia is pointing out that people reaching for their most familiar tool is likely why s is more upvoted than this answer.)
    – Caesar
    Nov 13, 2023 at 23:07
16

You can use cat -

printf '%s' "some text at the beginning" | cat - filename
5
  • 8
    This would only output the text followed by the file's content, but it does not modify the file at all.
    – Adaephon
    Feb 19, 2015 at 14:16
  • That's a good solution, I wonder why it didn't get any upvotes. Here's mine my good sir. Also, why printf and not a simple echo ?
    – ychaouche
    Jun 22, 2015 at 13:38
  • 1
    @ychaouche - presumably because there's no portable way to prevent echo from adding a newline? Mar 30, 2016 at 9:47
  • I tried directing this into a file by appending > file to the command, it jus spammed my terminal with "some text at the beginning"
    – minseong
    May 10, 2017 at 11:29
  • 2
    printf '%s' "some text" | cat - filename > tmpfile && mv tmpfile filename
    – luca
    Oct 18, 2019 at 23:49
12

To add a line to the top of the file:

sed -i '1iText to add\'
1
  • This includes a newline, which the questioner explicitly doesn't want. Mar 30, 2016 at 9:20
12

my two cents:

sed -i '1i /path/of/file.sh' filename

where /path/of/file.sh is the text you want to add.

This will work even if the string contains a forward slash "/"

1
  • This includes a newline, which the questioner explicitly doesn't want. Aug 3, 2023 at 10:53
9

Hi with carriage return:

sed -i '1s/^/your text\n/' file
9

Note that on OS X, sed -i <pattern> file, fails. However, if you provide a backup extension, sed -i old <pattern> file, then file is modified in place while file.old is created. You can then delete file.old in your script.

2
  • 4
    Or sed -i '' file. Then it'll just edit in-place and not make backups.
    – Harv
    Jul 14, 2015 at 20:23
  • 1
    I've found macOS sed wants a dot to edit in place without creating a backup: sed -i. <pattern> file Nov 30, 2019 at 6:08
7

There is a very easy way:

echo "your header" > headerFile.txt
cat yourFile >> headerFile.txt
2
  • Ow... sorry, now that I realize that you wanted to add at the beginning and not a new line. Nov 30, 2017 at 2:06
  • But I wanted a new line. So thanks for the simplistic approach. Dec 21, 2017 at 2:20
4

PROBLEM: tag a file, at the top of the file, with the base name of the parent directory.

I.e., for

/mnt/Vancouver/Programming/file1

tag the top of file1 with Programming.

SOLUTION 1 -- non-empty files:

bn=${PWD##*/}    ## bn: basename

sed -i '1s/^/'"$bn"'\n/' <file>

1s places the text at line 1 of the file.

SOLUTION 2 -- empty or non-empty files:

The sed command, above, fails on empty files. Here is a solution, based on https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash/246841#246841

printf "${PWD##*/}\n" | cat - <file> > temp && mv -f temp <file>

Note that the - in the cat command is required (reads standard input: see man cat for more information). Here, I believe, it's needed to take the output of the printf statement (to STDIN), and cat that and the file to temp ... See also the explanation at the bottom of http://www.linfo.org/cat.html.

I also added -f to the mv command, to avoid being asked for confirmations when overwriting files.

To recurse over a directory:

for file in *; do printf "${PWD##*/}\n" | cat - $file > temp && mv -f temp $file; done

Note also that this will break over paths with spaces; there are solutions, elsewhere (e.g. file globbing, or find . -type f ... -type solutions) for those.

ADDENDUM: Re: my last comment, this script will allow you to recurse over directories with spaces in the paths:

#!/bin/bash

## https://stackoverflow.com/questions/4638874/how-to-loop-through-a-directory-recursively-to-delete-files-with-certain-extensi

## To allow spaces in filenames,
##   at the top of the script include: IFS=$'\n'; set -f
##   at the end of the script include: unset IFS; set +f

IFS=$'\n'; set -f

# ----------------------------------------------------------------------------
# SET PATHS:

IN="/mnt/Vancouver/Programming/data/claws-test/corpus test/"

# https://superuser.com/questions/716001/how-can-i-get-files-with-numeric-names-using-ls-command

# FILES=$(find $IN -type f -regex ".*/[0-9]*")        ## recursive; numeric filenames only
FILES=$(find $IN -type f -regex ".*/[0-9 ]*")         ## recursive; numeric filenames only (may include spaces)

# echo '$FILES:'                                      ## single-quoted, (literally) prints: $FILES:
# echo "$FILES"                                       ## double-quoted, prints path/, filename (one per line)

# ----------------------------------------------------------------------------
# MAIN LOOP:

for f in $FILES
do

  # Tag top of file with basename of current dir:
  printf "[top] Tag: ${PWD##*/}\n\n" | cat - $f > temp && mv -f temp $f

  # Tag bottom of file with basename of current dir:
  printf "\n[bottom] Tag: ${PWD##*/}\n" >> $f
done

unset IFS; set +f
4

Just for fun, here is a solution using ed which does not have the problem of not working on an empty file. You can put it into a shell script just like any other answer to this question.

ed Test <<EOF
a

.
0i
<added text>
.
1,+1 j
$ g/^$/d
wq
EOF

The above script adds the text to insert to the first line, and then joins the first and second line. To avoid ed exiting on error with an invalid join, it first creates a blank line at the end of the file and remove it later if it still exists.

Limitations: This script does not work if <added text> is exactly equal to a single period.

4

The simplest solution I found is:

echo -n "<text to add>" | cat - myFile.txt | tee myFile.txt

Notes:

  • Remove | tee myFile.txt if you don't want to change the file contents.
  • Remove the -n parameter if you want to append a full line.
  • Add &> /dev/null to the end if you don't want to see the output (the generated file).
  • This can be used to append a shebang to the file. Example:
    # make it executable (use u+x to allow only current user)
    chmod +x cropImage.ts
    # append the shebang
    echo '#''!'/usr/bin/env ts-node | cat - cropImage.ts | tee cropImage.ts &> /dev/null
    # execute it
    ./cropImage.ts myImage.png
    
6
  • 1
    This appends the text twice in the same line Jan 26, 2022 at 6:37
  • 1
    It also replaces the content of the entire file. Jan 26, 2022 at 6:41
  • @DavidHeisnam, yes it replaces the file, unless you remove the tee pipe (I have updated the answer). But It won't append the text twice. You may have run the command twice. It's working in bash and zsh. Jan 26, 2022 at 7:07
  • 1
    In a for loop (in bash on OSX) it replaces the contents with only the text that should be added. Without for it worked for me
    – flexus
    Oct 17, 2022 at 12:54
  • I confirm this does not retain the original file contents Feb 3, 2023 at 10:33
2
echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt

The first tac pipes the file backwards (last line first) so the "text to insert" appears last. The 2nd tac wraps it once again so the inserted line is at the beginning and the original file is in its original order.

2
  • 1
    Can you please explain how this would help Tomas with the issue?
    – John Odom
    Jun 5, 2015 at 20:56
  • tac | tac -- that's how non-scalable mindsets form :-( May 22, 2018 at 12:55
1

cat concatenates multiple files. <() sends output of a command as a file. echo doesn't add new lines with -n switch. head command with -c switch can remove trailing newline in files. Combining all these, we can insert text at the beginning and end of a file without any new lines by,

cat <(echo -n "line before the file") <(head -c -1 file.txt) <(echo -n "line after the file")
1
  • head -c -1 doesn't work on bsd (& Macs) so please use ghead from coreutils May 26, 2023 at 9:26
1

thanks to all the top answers above, just a small hint:

for the sed approach, if you want to pass a variable while going to a newline, like what I've wanted to do with my /etc/hosts file, don't forget to use double quotes "

sed -i "1s/^/127.0.0.1 $HOSTNAME \n/" /etc/hosts

0
0

Another solution with aliases. Add to your init rc/ env file:

addtail () { find . -type f ! -path "./.git/*" -exec sh -c "echo $@ >> {}" \; }
addhead () { find . -type f ! -path "./.git/*" -exec sh -c  "sed -i '1s/^/$@\n/' {}" \; }

Usage:

addtail "string to add at the beginning of file"
addtail "string to add at the end of file"
0

With the echo approach, if you are on macOS/BSD like me, lose the -n switch that other people suggest. And I like to define a variable for the text.

So it would be like this:

Header="my complex header that may have difficult chars \"like these quotes\" and line breaks \n\n "

{ echo "$Header"; cat "old.txt"; } > "new.txt"
mv new.txt old.txt
0

TL;dr -

Consider using ex. Since you want the front of a given line, then the syntax is basically the same as what you might find for sed but the option of "in place editing" is built-in.

I cannot imagine an environment where you have sed but not ex/vi, unless it is a MS Windows box with some special "sed.exe", maybe.

sed & grep sort of evolved from ex / vi, so it might be better to say sed syntax is the same as ex.

You can change the line number to something besides #1 or search for a line and change that one.

source=myFile.txt
Front="This goes IN FRONT "
man true > $source
ex -s ${source} <<EOF
1s/^/$Front/ 
wq
EOF
$ head -n 3 $source
This goes IN FRONT TRUE(1)                                                    User Commands                                                    TRUE(1)

NAME

Long version, I recommend ex (or ed if you are one of the cool kids).

I like ex because it is portable, extremely powerful, allows me to write in-place, and/or make backups all without needing GNU (or even BSD) extensions.

Additionally, if you know the ex way, then you know how to do it in vi - and probably vim if that is your jam. Notice that EOF is not quoted when we use "i"nsert and using echo:

str="+++ TOP +++" && ex -s <<EOF
r!man true
1i
`echo "$str"`
.
"0r!echo "${str}"
wq! true.txt
EOF

0r!echo "${str}" might also be used as shorthand for :0read! or :0r! that you have likely used in vi mode (it is literally the same thing) but the : is optional here and some implementations do not support "r"ead address of zero. "r"eading directly to the special line #0 (or from line 1) would automatically push everything "down", and then you just :wq to save your changes.

$ head -n 3 true.txt | nl -ba   
     1  +++ TOP +++
     2  TRUE(1)                          User Commands                         TRUE(1)
     3  

Also, most classic sed implementations do not have extensions (like \U&) that ex should have by default.

0
find . -name "*prod*" -exec sed -i '1i\line1\n  Line2\n     Line3\n' {} \;

I use it to resolve this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.