Unix command to prepend text to a file

Is there a Unix command to prepend some string data to a text file?

Something like:

prepend "to be prepended" text.txt

Solution 1:

printf '%s\n%s\n' "to be prepended" "$(cat text.txt)" >text.txt

Solution 2:

sed -i.old '1s;^;to be prepended;' inFile
  • -i writes the change in place and take a backup if any extension is given. (In this case, .old)
  • 1s;^;to be prepended; substitutes the beginning of the first line by the given replacement string, using ; as a command delimiter.

Solution 3:

Process Substitution

I'm surprised no one mentioned this.

cat <(echo "before") text.txt > newfile.txt

which is arguably more natural than the accepted answer (printing something and piping it into a substitution command is lexicographically counter-intuitive).

...and hijacking what ryan said above, with sponge you don't need a temporary file:

sudo apt-get install moreutils
<<(echo "to be prepended") < text.txt | sponge text.txt

EDIT: Looks like this doesn't work in Bourne Shell /bin/sh


Here String (zsh only)

Using a here-string - <<<, you can do:

<<< "to be prepended" < text.txt | sponge text.txt