Skip to content

Instantly share code, notes, and snippets.

@spencerwi
Last active December 23, 2015 00:49
Show Gist options
  • Save spencerwi/6556168 to your computer and use it in GitHub Desktop.
Save spencerwi/6556168 to your computer and use it in GitHub Desktop.
Convert TSV on stdin to CSV on stdout
import Data.List
import Text.Regex
encloseField :: String -> String
encloseField field
| "," `isInfixOf` field = "\"" ++ (escapeField field) ++ "\""
| otherwise = escapeField field
escapeField :: String -> String
escapeField field
| "\"" `isInfixOf` field = subRegex (mkRegex "\"") field "\"\""
| otherwise = field
fieldsToCSV :: [String] -> String
fieldsToCSV = (intercalate ",") . (map encloseField)
splitFields :: String -> [String]
splitFields = splitRegex (mkRegex "\t")
main = interact $ fieldsToCSV . splitFields
@spencerwi
Copy link
Author

Useful as a "filter" in vim: select TSV lines, and execute

:'<,'>!tsvtocsv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment