To avoid all problems with having to quote special characters etc. for use with sed
, use a quoted here-document:
cat - output.txt <<'END_COMMENTS' >newfile.txt
#$ -cwd
#$ -pe mpi 16
END_COMMENTS
This concatenates your three lines of extra text with the contents of your existing file output.txt
, and places the resulting text in newfile.txt
. You are then free to rename newfile.txt
into output.txt
if you want.
The cat
command is used with two arguments here:
-
; this instructs cat
to first read from standard input. The standard input stream will contain the here-document containing your header text.
output.txt
; this is your existing file. It will be read whenever the data arriving on standard input is all read.
Testing:
$ cat output.txt
AAAA
BBBB
CCCC
DDDD
The >
prompt at the start of the lines below is the secondary prompt of the bash
shell, used when more input is needed to complete a command.
$ cat - output.txt <<'END_COMMENTS' >newfile.txt
> #$ -cwd
> #$ -pe mpi 16
>
> END_COMMENTS
$ cat newfile.txt
#$ -cwd
#$ -pe mpi 16
AAAA
BBBB
CCCC
DDDD
Note that if the final output is supposed to be a bash
shell script, then the first line of your header should be a #!
-line with the absolute pathname of the bash
interpreter.
You could also just use printf
:
printf '%s\n' '#$ -cwd' '#$ -pe mpi 16' '' |
cat - output.txt >newfile.txt
Instead of a here-document, this uses printf
to generate the three lines of header text. The result will be the same, but it looks uglier and you need to understand the code to see what the header text actually looks like (unless you run it, obviously).
cat header originalfile > newfile
. If you inted to instead add lines "infile" (ie, without going with a secondary filename), you can indeed use sed (or even : ed) for this. – Olivier Dulac Jan 04 '21 at 22:18