The most portable way to do this is by using POSIX specified features of ex
.
$ cat file1
Jack and Jill
Went up the hill
To fetch a pail of water.
$ cat file2
Nursery Rhymes:
Epic Poems:
Classic Literature:
$ printf '%s\n' '0r !head -n 1 file2' x | ex file1
$ cat file1
Nursery Rhymes:
Jack and Jill
Went up the hill
To fetch a pail of water.
printf
is used to send commands to ex
.
0
is the address given to the r
ead command; it tells ex
to read in the specified text "after line 0" (i.e. before line 1).
!head -n 1 file2
means that instead of r
eading text directly from a file (a whole file), the head
command is executed first and its output is read in (at the specified position, line 0).
x
means save and exit.
This is fully POSIX compliant and portable.
If you were scripting this it would be good practice to check your assumptions: That file2
exists and is readable, and that file1
is readable and writable if it exists.
if [ -r file2 ] && [ -f file2 ] && { ! [ -e file1 ] || { [ -r file1 ] && [ -w file1 ];};}; then
printf '%s\n' '0r !head -n 1 file2' x | ex file1
fi