textsedsld

How to copy & paste text between text using SED


I am trying to use SLD (Styled Layer Descriptor) to color a layer that will be displayed on a mapping server, however there's an error in my SLD so the colors are wrong. This is because the SLD is using random Hex values for Fill value. The right Hex values are in the SLD but they're not in the right place (they're used as layer names).

Here's a snippet from the SLD that colors one feature (there's ~850 others).

<se:Name>#27D1D1</se:Name>
      <se:Description>
        <se:Title>#27D1D1</se:Title>
      </se:Description>
      <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
        <ogc:PropertyIsEqualTo>
          <ogc:PropertyName>HEXCOLOR</ogc:PropertyName>
          <ogc:Literal>#27D1D1</ogc:Literal> <--I want this Hex value
        </ogc:PropertyIsEqualTo>
      </ogc:Filter>
      <se:PolygonSymbolizer>
        <se:Fill>
          <se:SvgParameter name="fill">#cd42a3</se:SvgParameter>  <--- Put here
        </se:Fill>
        <se:Stroke>
          <se:SvgParameter name="stroke">#000001</se:SvgParameter>
          <se:SvgParameter name="stroke-width">1</se:SvgParameter>
          <se:SvgParameter name="stroke-linejoin">bevel</se:SvgParameter>
        </se:Stroke>
      </se:PolygonSymbolizer>
    </se:Rule>
    <se:Rule>

Is there a way SED or similar could copy and paste the Hex value from Literal to Fill?


Solution

  • I think this does what you want:

    awk '/ogc:Literal/{split($0,a,/[><]/);hex=a[3]} /se:SvgParameter name="fill"/{sub(/#[0-9a-fA-F]*/,hex)} 1' YourFile
    

    So, that says... "If you see the string ogc:Literal, split the line using > and < as separators and put the elements into array a. Save a[3] in a variable called hex for later use. If you see a line containing se:SvgParameter name="fill", substitute anything that looks like a hex value in that line with the variable hex you remembered earlier. The 1 at the end means awk should do its default action, which is to print the line."

    If you want to save the modified file, use:

    awk ... YourExistingFile > ModifiedFile