title: Ruby one-liners: Writing a — POSIX shell compatible — TSV format
body: <p>I'm looking for a <strong>concise</strong> way of outputting TSV records that can be accurately read and unescaped with a POSIX shell (<code>IFS='&lt;TAB&gt;' read -r</code> + <code>printf %b</code>).</p>
  <p>The minimalist escaping rules are:</p>
  <ul>
  <li><code>\\</code> for backslash</li>
  <li><code>\n</code> for newline</li>
  <li><code>\t</code> for tab</li>
  <li><code>\r</code> for carriage return</li>
  </ul>
  <p>But they can be extended to the <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html#tag_20_94_13" rel="nofollow noreferrer"> full supported set</a> of <code>printf</code>, if there exists an easy way of doing it with ruby.</p>
  <p>The code so far:</p>
  <pre class="lang-rb prettyprint-override"><code>record = [ &quot;\\&quot;, &quot;\t&quot;, &quot;\n&quot;, &quot;\r&quot;, &quot;\&quot;&quot; ]
  
  rules = {
    &quot;\\&quot; =&gt; &quot;\\\\&quot;,
    &quot;\t&quot; =&gt; &quot;\\t&quot;,
    &quot;\r&quot; =&gt; &quot;\\r&quot;,
    &quot;\n&quot; =&gt; &quot;\\n&quot;
  };
  
  regex = /#{ rules.keys.map{|c| Regexp.escape(c)}.join(?|) }/;
  
  puts record.map { |field| field.gsub(regex) {|c| rules[c]} }.join(&quot;\t&quot;)
  </code></pre>
  <p>Output:</p>
  <pre><code>\\  \t  \n  \r  &quot;
  </code></pre>
  <p>The main problem is that the code is meant for one-liners, thus, if possible, I would like to reduce it greatly. Any ideas?</p>