How do I redirect shell stdout to the first line of file?

To write the date to the beginning instead of the end of file, try:

{ date; cat file; } >file.new && mv file.new file

Discussion

  1. Adding new text to the beginning of a file requires the whole file to be rewritten. Adding new text to the end of a file only requires writing the new text.

  2. Andy Dalton's suggestion of just appending to the end of a file like normal and then using tac file to view the file is a good one.

  3. echo `date` >> test.txt can be replaced by a simpler and more efficient date >> test.txt.

    If one is using bash 4.3 or later then, as Charles Duffy points out, printf '%(%c)T\n' -1 >>test.txt is still more efficient.

  4. The spaces around the curly braces are essential. This is because { and } are shell reserved words (as opposed to shell keywords which do not require spaces).


Try using sed :

sed -i "1 i\
$(date)" test.txt

Form man :

i \
text Insert text, which has each embedded newline preceded by a backslash.


Reverse order of lines

ex -s +%g/^/m0 +wq file

ex -s mode of vim editor, equivalent vim -nes
+wq command save and exit
or for bash

tac <<<$(<file) >file

<<<$(<file) this design serves as a self-made buffer

Writing to the first line

cat <<<$(date)$'\n'$(<file) >file
echo -e "$(date)\n$(<file)" >file

and

ex -s +'0r!date' +wq file

Sorry, I didn't get it right at first

Tags:

Shell

Bash