In the question How to append multiple lines to a file the OP was seeking a way to append multiple lines to a file within the shell. The solution:
cat <<EOT >> test.txt
line 1
line 2
EOT
I want to prepend lines and my attempt looks like:
echo 3 >test.text
cat test.text <<EOT >> test.text
1
2
EOT
But this results in an error:
cat: test.text: input file is output file
EDIT: for clarification, I am following a long server setup guide with instructions to manually edit configuration files. Editing at times involves prepending blocks of text to a file. In automating some of the steps, I want to retain the verbosity of the command by copying the text from the guide as-is and putting into a bash one-liner. For this reason the multi-line text input using EOT
is preferred.
EDIT: other answers using sed require backslashes to be appended to the end of each line but I want to enter multiple lines without modification.
Is there a way to prepend multiple lines to a file in a similar fashion above (ideally without a temporary file and installing moreutils
)?
cat
(but without reading or writing anything yet) and it can detect that you will overwrite your file and gives an error. The solution is to use a program that can rewrite a file (perl -i
comes to mind) and not the shell. – Thorbjørn Ravn Andersen Jan 28 '19 at 16:45