If it is permissible to replace the input file :
Note. This may have unexpected side effects , especially when replacing a symbolic link to a regular file, possibly ending with different file permissions and changing the file creation (birth) date .
sed -i , as in Prince John Wesley's answer, is trying to at least restore the original permissions, but other restrictions apply .
{ printf 'line 1\nline 2\n'; cat text.txt; } > tmp.txt && mv tmp.txt text.txt
Note. Using a group command { ...; ... } { ...; ... } more efficient than using a subshell ( (...; ...) ).
If the input file needs to be edited in place (keeping your inode with all its attributes) :
Using the venerable ed POSIX Utility :
Note: ed always reads the entire input file into memory.
ed -s text.txt <<'EOF' 1i line 1 line 2 . w EOF
-s suppressed ed status messages.- Notice how the commands are provided by
ed as a multi -line document here ( <<'EOF' ... EOF ), i.e. via STDIN. 1i makes 1 (1st row) the current row and starts insert mode ( i ).- The following lines are the text to be inserted before the current line, ending
. in its line. w writes the result back to the input file (for testing, replace w with ,p only to print the result without changing the input file).
mklement0 May 22, '15 at 3:00 2015-05-22 03:00
source share