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?

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.

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

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

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.

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.

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.

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

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.