BASH Prepend A Text / Lines To a File

I am a new Unix system user with a bash as a default shell. I can append text to a file using >> operator but how do I prepend a text to a file? I want the opposite operation of >>. How can I prepend some data to a text file? How do we add text to the beginning of a file in Bash under Linux?

Linux and Unix command to prepend text to a file

ADVERTISEMENTS

As far as I know there is no prepend operator on a bash or any other shell, however there are many ways to do the same. You can use ed, sed, perl, awk and so on to add text to the beginning of a file in Bash under Linux or Unix-like systems.

Bash prepend a text using a temporary file

Here is simple solution using a temporary file to prepend text:

echo 'line 1' > /tmp/newfile
echo 'line 2' >> /tmp/newfile
cat yourfile >> /tmp/newfile
cp /tmp/newfile yourfile

Here is one line solution:

echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile
echo "nixCraft"|cat - yourfile > /tmp/out && mv /tmp/out yourfile
BASH Prepend A Text or Lines To a File Under Linux and Unix

Prepending A Text or Lines To a File Under Linux and Unix

Using bash only solution to add text to the beginning of a file

No need to create a temp file. The syntax is:

echo -e "DATA-Line-1\n$(cat input)" > input
cat input

To add multiple lines:

echo -e "DATA-Line-1\nDATA-Line-2\n$(cat input)" > input
cat input

For example add text to the beginning of a text file called input using bash as follows:

cat input
echo -e "Famous Quotes\n$(cat input)" > input
Linux bash append text at file begin

Use sed command to prepend data to a text file

The syntax is follows to prepend A text or lines to a file when we use the sed command:

sed  '1s;^;DATA-Line-1\n;' input > output
## GNU/sed syntax ##
sed -i '1s;^;DATA-Line-1\n;' input
## Verify it using the cat ##
cat input

Here is a sample input file:

$ cat input.txt
This is a test file.
I love Unix.

Next prepend two lines (make sure you add \n):

$ sed -i '1s;^;Force-1\nForce-2\n;' input.txt
$ cat input.txt
Force-1
Force-2
This is a test file.
I love Unix.

How do I prepend a string to the beginning of each line in a file?

The awk command syntax is:

awk '{print "Line-1" $0}' file
## add a new line for each matched line ##
awk '{print "~~~~~~~~\n" $0}' quotes.txt > output.txt

Display result using the [nicmd name=”cat”] or grep command/egrep command:
$ cat output.txt
The sed syntax is:

sed -i -e 's/^/Line-1/' file
awk pretend text

Examples

Here is our sample file:

$ cat data.txt
Maybe I'm crazy
Maybe you're crazy
Maybe we're crazy
Probably

Use the sed or awk as follows:

$ sed -i -e 's/^/DATA-Here/' data.txt
$ cat data.txt
DATA-HereMaybe I'm crazy
DATA-HereMaybe you're crazy
DATA-HereMaybe we're crazy
DATA-HereProbably

Conclusion

You learned how to prepend a text or lines to a file when using bash and other command-line utilities. See sed,awk, and bash command man pages for more info using the man command:
$ man bash
$ man sed
$ man awk

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
41 comments… add one
  • Sean Aug 23, 2008 @ 14:11

    perl -p -i -e 'BEGIN { print "First line\n" }' originalfile

    should work without needing an explicit temp file

    If you’re going to use these commands in a script, though, “man mktemp” first.

    Sean

  • Professor Fapsanders Aug 23, 2008 @ 19:19

    Even simpler would be:
    sed -i '1i Prepended line' /tmp/newfile

    • A.Lepe Jul 28, 2011 @ 1:49

      +1 This works very nice and without using temporally files.

      • Sigurt Bladt Dinesen Jan 29, 2013 @ 14:54

        Works, but it _does_ use a temporary file behind the covers.
        The following is from the info document:
        >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        --in-place[=SUFFIX]'
             This option specifies that files are to be edited in-place.  GNU
             `sed' does this by creating a temporary file and sending output to
             this file rather than to the standard output.(1).
        

        <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    • nikolocalhost Aug 1, 2011 @ 21:28

      That works on linux but not in solaris (unless you install gsed package), because de solaris sed command doesnt support “in place option” -i.

      In that case

      echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile

      works for me

      Thanks for help :)

      • Craig Jun 12, 2013 @ 6:00

        Yes it does. The `-i` option is a mandatory part of POSIX, so it will work on any UNIX that takes itself seriously, Solaris included.

        It just works differently, i.e. GNU sed allows you to omit the argument of the `-i` flag, as was done in the example, whereas most other seds require it.

        Try:

        sed -i.bak '1i Prepended line' /tmp/newfile

        Now hang your head in shame.

        • Craig Jun 12, 2013 @ 6:03

          Ok, I was wrong on the POSIX part, I will hang my head in shame.

          ..but the missing flag argument is probably still the reason the example didn’t work on Solaris.

    • Paul Pignon Sep 8, 2012 @ 8:41

      Yes, that worked very nicely for me in Linux armel 2.6.32-rc5, sed is great but if you don’t use it regularly for a month it’s RTFM every time. Thanks.

    • felipe1982 Mar 27, 2013 @ 4:54

      Excellent suggestion with `sed` very good.

  • mike Aug 24, 2008 @ 17:51

    You can also use tac (cat backwards) to make it work. It will print the file from end to beginning.

  • bc Dec 29, 2008 @ 4:15

    Thread’s old, I know, but I wanted to note that tac -- at least in the version I have in Cygwin, is not fully “cat in reverse” alas.

    As you say, it’ll print from the end — but it won’t take an argument like this:

    tac >> somefilethatyouwanttoPREPENDtextto

    Just thought I’d note that for others who might be searching the same issue as the OP.
    This seems like such an obviously useful utility it’s unbelievable what a pita it is.

  • nairbv Aug 17, 2009 @ 10:57

    I tried the perl command (same one suggested to me by someone on IRC) and it didn’t work. It just printed to stdout and left the file unchanged. I’m kind of surprised two different people suggested the exact same non-working command, so I must be doing something wrong. What could I be doing wrong though??

    I like the sed command, but I needed to add more than one line (and my text contained special characters).

    This worked for me:

    sed -i '1{h; r headerfile.txt
    D;}
    2{x; G; }
    ' filetoedit.txt
    

    I’m not even really sure how it works, I just combined bits of code from a couple of random scripts I saw elsewhere. I should learn more sed :-P

    this also worked:

    for FILE in `find . -iname "*.php"`
    do
     cat header.php | cat - $FILE > /tmp/mytmpfile && mv /tmp/mytmpfile $FILE
    done
    
  • Victor Jul 21, 2010 @ 16:48

    tac your_file prepended_text | tac > your_new_file

  • SilversleevesX Sep 18, 2010 @ 1:10

    tac does not add a damn thing.
    Given this command:

    tac biglist.txt "thisistext" > biglist5.txt
    

    — I get the error
    tac: cannot open `thisistext’ for reading: No such file or directory.
    Considering it’s a close cousin of cat, I shouldn’t expect it to do any more, logically.
    Please do the newbie world a favour and remove any references to tac in this thread.

    BZT

    • jbo5112 Oct 12, 2010 @ 16:57

      You need to put your prepend data into the file “thisistext”. Also, unless you want your file to come out upside down, you’ll have to pipe the output from the first tac into a second tac before redirecting to a file.

    • jbo5112 Oct 12, 2010 @ 17:49

      With a little creative use of shell commands, you can avoid needing a second input file. Passing ‘-‘ as an argument tells most tools to use standard input or output (whichever applies) as a file.

      echo "my_prepend_text_goes_here" | tac biglist.txt - | tac > biglist5.txt

      There are a couple of tricks where you can avoid needing to create biglist5.txt in the process (storing results to a variable or using “tee” to write your output), but I can’t find anything that will work on large files.

      • Ladd Jun 17, 2011 @ 16:28

        This is clever; even simpler, you can use
        echo “prepend this” | cat – file.txt > newfile.txt

  • SilversleevesX Sep 18, 2010 @ 1:19

    How about a command or script to add the same text to every line OF a file, not just to the file itself???

    Believe it or not
    bash prepend same text to beginning of all lines of file
    does not have an exact match on Google. Ask.com and Yahoo! were sloppy with it (read:inexact and wide of the mark ultimately). Just more proof to my assertion that the world is going stupid.

    BZT

    • Q Sep 21, 2010 @ 15:22

      This can be done with sed in place (a pretty scary operation):

      sed -i -e 's/^/PREFIX/' file_with_lines_to_prefix.txt

      • Mark Stafford Feb 8, 2011 @ 19:27

        Thanks, Q. I’ve attempted something similar in the past without success.

  • Matt Jan 21, 2011 @ 20:16

    This perl one-liner will prefix (not prepend, which isn’t a word) a line to the beginning of a file.

    perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt

    (from the perl FAQ):

    • jbo5112 Jan 25, 2011 @ 17:08

      You got gypped on your dictionary if it doesn’t have prepend.
      http://www.dict.org/bin/Dict?Form=Dict2&Database=*&Query=prepend

      It’s also in the Merriam-Webster Unabridged Dictionary, which is more authoritative at the cost of a subscription, and it’s even a command in the popular jQuery javascript library. However, I agree prefix would be more proper English if one cares and has an educated audience that would not be confused.

      • jbo5112 Jan 25, 2011 @ 17:09

        You’ll have to copy and paste the url, as the link parser cannot handle it.

      • Ladd Jun 17, 2011 @ 16:31

        ‘prepend’ is a corollary to ‘append’, which is an English word.

  • niemand Jul 13, 2011 @ 9:51

    Ugh, my original message totally got garbled…

    What the above SHOULD look like:

    From http://sed.sourceforge.net/grabbag/tutorials/sedfaq.txt:

    sed '1{h; r file_to_prepend.txt
    D; }
    2{x; G; }' < file_to_be_prepended
    

    This can be used to insert a file into any line but the last one into a second file. For instance, to insert file1 into file2 at line 10:

    sed '10{h; r file1
    D; }
    11{x; G; }' <file2
    

    Edited by Admin – added formatting html tags

  • jbo5112 Jul 29, 2011 @ 0:32

    You could generate a patch file and use patch.

    diff -u <(head myfile) mypatch; patch mypatch

    • jbo5112 Jul 29, 2011 @ 0:33

      That got completely mangled. Is there any way to protect my comments?

      • jbo5112 Jul 29, 2011 @ 0:46

        My finally correct version (may I request a preview feature?):

        diff -u <(head myfile) <(echo -e "my data goes here and ends at the period.\n`head myfile`") > mypatch; patch mypatch
    • jbo5112 Jul 29, 2011 @ 0:41

      Let’s try again.

      diff -u <(head myfile)  mypatch; patch mypatch
    • jbo5112 Jul 29, 2011 @ 0:44
      diff -u <(head -n 50 votd) <(echo -e "my data goes here and ends at the period.\n`head -n 50 votd`") > mypatch; patch mypatch
  • jbo5112 Jul 29, 2011 @ 0:39

    Another method is using ed:

    echo -e “0a\nmy data goes here and ends at the period.\n.\n,wq” | ed myfile

    • niemand Sep 10, 2011 @ 11:50

      A variation on this is:

      echo “0r header.txt
      w” | ed myfile.txt

  • Muhammad El-Sergani Oct 14, 2011 @ 9:20

    Thanks, works well…

  • mariomaric Oct 22, 2011 @ 15:14

    This is the best (sed) one-liner that I found for this problem:

    sed -i -e '1i TEXT' FILE

    Above command will insert string TEXT into the first line of the file FILE.

  • ladistec Sep 20, 2012 @ 16:45

    echo "MAINCARD_MSISDN,SUB_SOC,EXPIRY_DATE,S,U," | cat - $spoolFile > /tmp/out && mv /tmp/out $spoolFile

    that line above works for. problem is if a have to run the script more than once. it will insert the same line again.. Any way to stop it?

    thanks

    • jbo5112 Jan 8, 2013 @ 20:09
      if ! head -n 1 "$spoolFile" | fgrep "$myString" &>/dev/null; then
        echo "$myString" | cat - "$spoolFile" > /tmp/out && mv /tmp/out "$spoolFile"
      fi
      
  • nick Nov 2, 2016 @ 17:54

    Its worth mentioning that

    echo -e "DATA-Line-1\n$(cat input)" > input

    Is very ineficient and works only for small files, the larger files (e.g. 800Mb) crash the terminal and leave the file empty.

  • sas Dec 30, 2016 @ 14:54


    echo -e "DATA-Line-1\n$(cat input)" > input

    dose not always work

    bash-4.1$ cat fish
    VALUE=${VALUE//[$'\t\r\n']}
    
    bash-4.1$ echo -e "DATA-Line-1\n$(cat fish)" > fish
    bash-4.1$ cat fish
    DATA-Line-1
    VALUE=${VALUE//[$'	
    ']}
    
  • RgnKjnVA Apr 6, 2017 @ 16:44

    This is the only sed syntax that works for me on OSX Sierra:

    sed -i_bak '1s;^;prepended text ;' test.file

    Thanks, I’d been looking for an hour.

  • Brodie Davis Apr 7, 2017 @ 13:17

    Thanks, this pointed me to just what I needed! I wanted to point out that your “Bash Only” way doesn’t need to be bash only – instead of using $(cat input), use `cat input` (use the backtick character). It does the same thing as $() in bash, but it works in most shells :D

  • Dave May 8, 2017 @ 0:58

    Thank you
    sed -i '1s;^;DATA-Line-1\n;' input” worked great!
    Just what I needed

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.