Using ‘sed’ to repace text in a file

I have 100 .svg files in a directory that I wanted to crop by one pixel on each side. This was an automatically generated 1 px wide white border, so it was controlled by only a single line in the .svg file specifying a white box from 0,0 to 31,31. The hard way would be to use Inkscape to modify each file individually, but once again ‘sed’ can come to the rescue and modify all 100 files with one command.

The pertinent line that I needed to change was

<rect x=”0″ y=”0″ width=”31″ height=”31″ fill=”#FFFFFF” />
<rect x=”1″ y=”1″ width=”29″ height=”29″ fill=”#FFFFFF” />

so we invoke ‘sed’ with

# sed -i 's/x="0" y="0" width="31" height="31"/x="1" y="1" width="29" height="29"/1' *.svg

The ‘-i’ switch tells ‘sed’ to modify the files in place and the ‘s/regexp/replacement/’ defines the string to search for and replace. the ‘/1′ switch on the end tells ‘sed’ to operate only on the 1st instance of the matched expression.

Leave out the ‘-i’ switch and operate on a single file to preview the changes to stdout before committing.

And voila! 100 files fixed in no time!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>