Convert quad mesh OBJ to triangle mesh OBJ using regular expressions (with bash and sed)

Here’s a simple bash one-liner that converts a quad mesh stored in an OBJ file into a triangle mesh stored in a OBJ file. It splits every quad (a,b,c,d) into two triangles (a,b,c) and (a,c,d).

I issue this in the bash shell of my mac (you may have to tweak the sed syntax):


cat quads.obj | sed -E -e "s/f ([0-9\/]+) ([0-9\/]+) ([0-9\/]+) ([0-9\/]+)/f \1 \2 \3`echo -e "\r"`f \1 \3 \4/g" > triangles.obj

Or I open the file with vim and use:


:%s/f \([0-9\/]\+\) \([0-9\/]\+\) \([0-9\/]\+\) \([0-9\/]\+\)/f \1 \2 \3\rf \1 \
3 \4/g

Tags: , , , , , , , , ,

2 Responses to “Convert quad mesh OBJ to triangle mesh OBJ using regular expressions (with bash and sed)”

  1. Tarethriel says:

    Holy crap this is awesome! We are building a renderer in my computer graphics class, and we are using tris. However, the model I had in blender was in quads. Turns out the new blender only does tris to quads, so this program was extremely useful! Thanks!

  2. gnif says:

    Thanks for this, but it is technically incorrect. I have seen many files that contain tons of entries for a face entry, through experimentation I have determined that the format is actually a triangle strip. To correctly convert to triangles all you need to do use a sliding window, for example:

    f A B C D E F

    Becomes the following triangles

    A B C
    A C D
    B D E
    C E F

    This will both render quads and triangles correctly with the same code :)

Leave a Reply