BASH: Prepend A Text / Lines To a File

by on August 23, 2008 · 36 comments· LAST UPDATED August 23, 2008

in , ,

Q. I can append text to a file using >> operator but how do I prepend a text to a file? I want the opposit of >> operation?

A. There is no prepend operator, however there are many ways to do the same. You can use ed, sed, perl, awk and so on.

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
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 36 comments… read them below or add one }

1 Sean August 23, 2008 at 2:11 pm

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

Reply

2 Professor Fapsanders August 23, 2008 at 7:19 pm

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

Reply

3 A.Lepe July 28, 2011 at 1:49 am

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

Reply

4 Sigurt Bladt Dinesen January 29, 2013 at 2:54 pm

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).
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Reply

5 nikolocalhost August 1, 2011 at 9:28 pm

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 :)

Reply

6 Craig June 12, 2013 at 6:00 am

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.

Reply

7 Craig June 12, 2013 at 6:03 am

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.

Reply

8 Paul Pignon September 8, 2012 at 8:41 am

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.

Reply

9 felipe1982 March 27, 2013 at 4:54 am

Excellent suggestion with `sed` very good.

Reply

10 mike August 24, 2008 at 5:51 pm

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

Reply

11 bc December 29, 2008 at 4:15 am

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.

Reply

12 nairbv August 17, 2009 at 10:57 am

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

Reply

13 Victor July 21, 2010 at 4:48 pm

tac your_file prepended_text | tac > your_new_file

Reply

14 SilversleevesX September 18, 2010 at 1:10 am

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

Reply

15 jbo5112 October 12, 2010 at 4:57 pm

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.

Reply

16 jbo5112 October 12, 2010 at 5:49 pm

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.

Reply

17 Ladd June 17, 2011 at 4:28 pm

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

Reply

18 SilversleevesX September 18, 2010 at 1:19 am

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

Reply

19 Q September 21, 2010 at 3:22 pm

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

sed -i -e ‘s/^/PREFIX/’ file_with_lines_to_prefix.txt

Reply

20 Mark Stafford February 8, 2011 at 7:27 pm

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

Reply

21 Matt January 21, 2011 at 8:16 pm

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):

Reply

22 jbo5112 January 25, 2011 at 5:08 pm

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.

Reply

23 jbo5112 January 25, 2011 at 5:09 pm

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

Reply

24 Ladd June 17, 2011 at 4:31 pm

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

Reply

25 niemand July 13, 2011 at 9:51 am

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

Reply

26 jbo5112 July 29, 2011 at 12:32 am

You could generate a patch file and use patch.

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

Reply

27 jbo5112 July 29, 2011 at 12:33 am

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

Reply

28 jbo5112 July 29, 2011 at 12:46 am

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

Reply

29 jbo5112 July 29, 2011 at 12:41 am

Let’s try again.

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

Reply

30 jbo5112 July 29, 2011 at 12:44 am
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

Reply

31 jbo5112 July 29, 2011 at 12:39 am

Another method is using ed:

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

Reply

32 niemand September 10, 2011 at 11:50 am

A variation on this is:

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

Reply

33 Muhammad El-Sergani October 14, 2011 at 9:20 am

Thanks, works well…

Reply

34 mariomaric October 22, 2011 at 3:14 pm

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.

All credits goes to user unknown for the answer @ stackoverflow.

Reply

35 ladistec September 20, 2012 at 4:45 pm

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

Reply

36 jbo5112 January 8, 2013 at 8:09 pm

if ! head -n 1 “$spoolFile” | fgrep “$myString” &>/dev/null; then
echo “$myString” | cat – “$spoolFile” > /tmp/out && mv /tmp/out “$spoolFile”
fi

Reply

Leave a Comment

Tagged as: , , , , , , ,

Previous Faq:

Next Faq: