#!/bin/sh # Parsing CSV files with sed # we convert csv files into a simplified interchange format: # text characters separated by tabs! we escape tabs, newlines, and backslashes # into \t, \n, and \\. # these functions process on standard input and standard output. # we allow CR LFs in input but we don't output them by default. # see csv.sh for an unminified version. # made by Natalia Posting in 2023 from_csv () { LC_ALL=C sed -n 's/'"$(printf "\r")"'$//;s/\\/\\\\/g;s/'"$(printf "\t")"'/\\t/g;H;x;h;s/^\n//;s/\n/\\n/g;s/,/,,/g;s/$/,/;s/^/,/;s/,\([^",]*\("[^"]*\(""[^"]*\)*"[^",]*\)*\),/\1'"$(printf "\t")"'/g;/,$/d;s/.$//;s/,,/,/g;s/"\([^"]*\(""[^"]*\)*\)"/\1/g;s/""/"/g;p;s/.*//;h' } to_csv () { LC_ALL=C sed 's/"/""/g;s/'"$(printf "\t")"'/","/g;s/^/"/;s/$/"/;s/\\\\/& /g;s/\\n/\n/g;s/\\t/'"$(printf "\t")"'/g;s/\\\\ /\\/g;' }