You can do:
sed -n '$d;w file2' >file1 <<IN
$(cat file1; echo .)
IN
Which will safely write every line from file1 into file2 while simultaneously deleting every line in file1. The shell handles the intermediate temp file securely - it creates one and then deletes it from its filesystem before ever writing a single byte to it.
As soon as sed
releases the file-descriptor (at EOF or when it terminates - whichever comes first) the file ceases to exist at all. Unlike the common sed -i
option, this does not depend on sed
cleaning up after itself (which may not happen if its processing is unexpectedly interrupted) and nor does it carry with it the same permissions inconsistencies the -i
option implies.
And the application need not be global as demonstrated - the lines can be either deleted from the original and/or written to the separate output selectively...
sed -n '$d;/pattern1/w file2
/pattern2/p' >file1 <<IN
$(cat file1; echo .)
IN
...demonstrates how only lines from file1 which match /pattern2/
will be printed back into file1 and only lines from same which match /pattern1/
are w
ritten to file2. Any other sed
command is of course applicable as well.
It is probably worth noting, though, that for most shells this will not carry over NUL bytes from file1 (which isn't often a concern for sed
work) - though such a thing is possible with zsh
.