Last active
December 23, 2015 00:49
-
-
Save spencerwi/6556168 to your computer and use it in GitHub Desktop.
Convert TSV on stdin to CSV on stdout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useful as a "filter" in vim: select TSV lines, and execute