-
-
Save chencang/9c4cf89c2d74fad301b9b9a818890f3c to your computer and use it in GitHub Desktop.
Demo to parse CSV file with awk.
This file contains hidden or 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
# parse csv files to an awk array. | |
awk -F, '{ | |
parse_csv(r); | |
# replace following line with your code. | |
print r[1], r[2], r[3], r[4]; | |
} function parse_csv(r, _quote, _i, _n) { | |
_i = 1; | |
_quote = 0; # in a quoted string or not. | |
for (_n = 1; _n <= NF; _n++) { | |
if (_quote) { | |
# quote string meets its end. | |
if (substr($_n, length($_n), 1) == "\"") { | |
_quote = 0; | |
r[_i] = r[_i]","substr($_n, 1, length($_n) - 1); | |
_i++; | |
} else { | |
# concat quote string with ",". | |
r[_i] = r[_i]","$_n; | |
} | |
} else { | |
# it is a quote string. | |
if (substr($_n, 1, 1) == "\"") { | |
_quote = 1; | |
r[_i] = substr($_n, 2); | |
} else { | |
# copy content for normal string without quote. | |
r[_i] = $_n; | |
_i++; | |
} | |
} | |
} | |
}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment