Search code examples
svgbatch-processingfillinkscapestroke

sed command to batch change fill and stroke of an SVG


I have a folder with around 300 SVG icons. It is all black. I would like to change the fill and stroke colours of all icons ( to shades of blue). It is a very hard job to do 300 through Inkscape. I saw some examples of using sed command to do it as a batch. But none suited my requirement.Can someone help me with this ? I am also open to other options. I tried IcoMoon as a GUI option, but not sure how to change the colour in it as a batch.

I am using Ubuntu 18.04.


Solution

  • I don't know exactly the structure of your SVG, but I will suppose that you use icons like font-awesome ones (SVG format).

    You say that the original color is black, so here we have multiples cases :

    1. there is no fill and stroke attribute in the XML
    2. the fill and stroke attribute can be with the values "black" or "currentValue"

    The script bellow takes the two cases in consideration :

    #/bin/sh
    COLOR=yellow
    sed -i -E 's/fill\="[^"]+"//g; s/stroke\="[^"]+"//g' *.svg
    sed -i "s/<path/<path fill=\"$COLOR\" stroke=\"$COLOR\"/g" *.svg
    

    you've just to set the destination color into the COLOR variable, and don't forget to run the script inside your folder.

    I tested the script for the font-awesome SVG icons, and it works.

    Let me know if it works for you.

    EDIT : For the ionicons (outline), try the script bellow :

    #/bin/sh
    COLOR=yellow
    sed -i -E 's/fill\="[^"]+"//g; s/stroke\="[^"]+"//g' *.svg
    sed -i "s/<path/<path fill=\"$COLOR\" stroke=\"$COLOR\"/g" *.svg
    sed -i "s/<rect/<rect fill=\"$COLOR\" stroke=\"$COLOR\"/g" *.svg
    sed -i "s/<polygon/<polygon fill=\"$COLOR\" stroke=\"$COLOR\"/g" *.svg
    sed -i "s/<circle/<circle fill=\"$COLOR\" stroke=\"$COLOR\"/g" *.svg
    sed -i "s/<ellipse/<ellipse fill=\"$COLOR\" stroke=\"$COLOR\"/g" *.svg
    sed -i "s/<polyline/<polyline fill=\"$COLOR\" stroke=\"$COLOR\"/g" *.svg
    sed -i -E "s/stroke\:[^\;]+/stroke\:$COLOR/g" *.svg
    sed -i -E "s/fill\:\#[0-9]+/fill\:$COLOR/g" *.svg