0

I would like to multiply the attribute in viewBox of svg-files by a factor of ten.

I want to change <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" version="1.1"> to <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" version="1.1"><g transform="scale(10)"> (I need it for a workaround of a librsvg-bug)

My current script looks like this:

#!/bin/bash

#defining file
export i=test.svg

#Define file as a variable
export h=$(sed -r 's/<svg ([-[:alnum:]=\" \.\/:\,]+) viewBox="([-[:digit:]]+) ([-[:digit:]]+) ([[:digit:]]+)\.([[:digit:]])([[:digit:]]*) ([[:digit:]]+)\.([[:digit:]])([[:digit:]]*)"([-[:alnum:]=\" \.\/:\,]+)>/<svg \1 viewBox="0 0 \2\3.\40 \5\6.\70"\8><g transform="scale(10)">/' $i)

#Reading out the relevant line
export j=$(ls -l|grep -E "viewBox=\"[-[:digit:].]{1,5} [-[:digit:].]{1,5} [[:digit:].]{3,7} [[:digit:].]{3,7}" $i)

#Insert a special character to define the point of splitting
export l=$(echo $j | sed -e "s/viewBox=\"/>/g" )

#split at this special character and take the part afterwards
export m=$(echo $l | cut -f2 -d">")

#Multiply the four numbers by a factor of 10
export n=$(echo $m | awk  '{printf "%f %f %f %f\n",$1*10,$2*10,$3*10,$4*10}')

#Replace the old four numbers with the new four numbers
sed -ri "s/<svg([-[:alnum:]=\" \.\/:;\,#]*) viewBox=\"[-[:digit:]\.]+ [-[:digit:]\.]+ [[:digit:]\.]+ [[:digit:]\.]+\"([-[:alnum:]=\" \.\/:\,]+)>/<svg \1 viewBox=\"$n\"\2><g transform=\"scale(10)\">/" $i

This is neither beautiful, nor always working. (for example it won't work if there is an inline svg in an mother-svg embedded (example))

You can use whatever you want it should:

  • Work on Ubuntu aswell on Cygwin
  • should be a batchcommand
  • Is it an absolute requirement that you use sed? It's suited neither to XML parsing, nor to arithmetic. awk can handle arithmetic, but to handle complex files you would need a dedicated XML parser (such as xmlstarlet). – JigglyNaga Dec 21 '18 at 15:54
  • 1
    @JigglyNaga The slight issue here is that xmlstarlet can't really poke inside the text attribute to modify its values. One would have to extract it, modify it by other means, and update the XML with the modified text string. – Kusalananda Dec 22 '18 at 10:32
  • @JigglyNaga I you know a working solution I would be happy. (sorry for the missleading title) – JoKalliauer Dec 22 '18 at 18:28

Your Answer

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

Browse other questions tagged or ask your own question.