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
    csplit splits up to but not including the pattern. – don_crissti Sep 8 '15 at 14:26
  • 1
    That is the default behaviour of csplit with the /pattern/ regexp form ("copy up to but not including a matching line"), so you should be able to use this answer from the question you linked, simply omitting the +1 offset. – steeldriver Sep 8 '15 at 14:26
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
1

Other variant (with sed)

sed '/XYZ/,${
             w file2
             d
            }' file >file1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.