mardi 4 août 2015

Powershell v2 - Select-String from pattern A to pattern B

Is there a way to use select-string to find all lines between X and Y.

e.g. if I have a file with content:

[line 157: Time 2015-08-04 11:34:00] 
<staff>
    <employee>
        <Name>Bob Smith</Name>
        <function>management</function>
        <age>39</age>
        <birthday>3rd June</birthday>
        <car>yes</car>
    </employee>
    <employee>
        <Name>Sam Jones</Name>
        <function>security</function>
        <age>24</age>
    </employee>
    <employee>
        <Name>Mark Perkins</Name>
        <function>management</function>
        <age>32</age>
    </employee>
</staff>

and I want to find all the content for < function >management< /function >, so I would end up with:

<employee>
    <Name>Bob Smith</Name>
    <function>management</function>
    <age>39</age>
    <birthday>3rd June</birthday>
    <car>yes</car>
</employee>
<employee>
    <Name>Mark Perkins</Name>
    <function>management</function>
    <age>32</age>
</employee>    

If all groupings were the same size I could use something like:

    select-string -Pattern '<function>management</function>' -CaseSensitive -Context 2,2

However, in reality they are not going to be the same size, so I can't use a fixed number each time.

Really I need a way of saying return everything that is:

2 rows above my search term
until
the following '</employee>' field

for all matching instances.

Is this possible?

I can't use the standard xml tools in powershell, as the file I am reading isn't standard xml hence I included [line 157: Time 2015-08-04 11:34:00] as an example. The best way to think of it is lots of xml files, all merged into one xml file, with the [line . . .] headers to break them up.

Aucun commentaire:

Enregistrer un commentaire