0

Can split be used to split a file into multiple segments where the size of each segment is based on the number of matches of an XML element ?

For example for below XML split when encounters of "<test xsi:type="update" locale="en_US">" is 2

<?xml version="1.0" encoding="UTF-8"?>
<testers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>
<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>
<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>
</testers>

Splitting the above XML file should generate 2 files.

file1 :

<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>
<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>

and file 2 containing just a single entry :

<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>

Here is what I'm trying :

split -p "<test xsi:type=\"update\" locale=\"en_US\">" test.xml segment

which outputs 4 files:

segmentaa :

<?xml version="1.0" encoding="UTF-8"?>
<testers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

segmentab :

<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>

segmentac :

<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>

segmentad :

<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>
</testers>

Can split be utilised in the way I'm suggesting. The file I'm processing is 40GB, I use the above example to illustrate the problem I'm trying to solve.

1

I don't think its possible with split. You could use awk:

awk '
  BEGIN{ 
    fmt="segment%02d"               # 2 digits for suffix, zero padded
    start="<test xsi:type=\"update\" locale=\"en_US\">"
    end="</test>"
  }
  $0 == start, $0 == end{
    if ($0 == start && ++cnt%2==1){ # for every 2nd start element...
      fname=sprintf(fmt, fcnt++)    # update output filename
    }
    print $0 > fname                # print line, redirect output to fname
  }
' test.xml

This produces two files segment00 and segment01:

$ head segment*
==> segment00 <==
<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>
<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>

==> segment01 <==
<test xsi:type="update" locale="en_US">
<rval>1</rval>
</test>

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.