1

This is an almost identical question to split file into two parts, at a pattern but instead of having the lines up to XYZ in file1 in the example file.txt:

ABC
EFG
XYZ
HIJ
KNL

I want to have the XYZ included in file2 (but XYZ is still the pattern to divide on). What I have now is using this answer: https://unix.stackexchange.com/a/202516/108861 and then adding the last line from file1 to the top of file2 and removing it from file1, but is there an easier one-line solution?

2 Answers2

3

It is very easy to modify my solution to the other question. Just remove the next:

perl -ne 'if(/XYZ/){$a=1} ; $a==1 ? print STDERR : print STDOUT;' file >f1 2>f2;

That will create f1 with everything up to XYZ and f2 with everything else, including the XYZ.


Alternatively, the accepted answer from the question you linked to already does pretty much what you need. It just keeps XYZ in the 1st file. To have it in the second, just invert the two awk commands:

awk '/XYZ/{out="file2"}{print >out}; ' out=file1 file
terdon
  • 242,166
1

Other variant (with sed)

sed '/XYZ/,${
             w file2
             d
            }' file >file1
Costas
  • 14,916