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

Alec Jacobson

December 15, 2010

weblog/

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