Thanks so much, this is a lifesaver. Great when working on Linux OS. I added one line to replace any comma already existing in the texts by '_' before writing contents. Important if you have chemical names in there.
...
elseif isempty(contents)
contents = '';
else
contents=strrep(contents, ',' , '_' );
end