Created
June 26, 2015 02:28
-
-
Save mrdwab/43f59d1d7e6cd373f455 to your computer and use it in GitHub Desktop.
Use awk to help convert fixed width to csv. Not tested extensively. Works based on stacks of spaces at common positions.
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
| fwf2csv <- function(infile) { | |
| if (infile == "clipboard") { | |
| infile <- tempfile() | |
| writeLines(overflow:::readClip(), infile) | |
| } | |
| a <- tempfile() | |
| text <- 'BEGIN{ FS=OFS=""; ARGV[ARGC]=ARGV[ARGC-1]; ARGC++ } | |
| NR==FNR { | |
| for (i=1;i<=NF;i++) { | |
| if ($i == " ") { | |
| space[i] | |
| } | |
| else { | |
| nonSpace[i] | |
| } | |
| } | |
| next | |
| } | |
| FNR==1 { | |
| for (i in nonSpace) { | |
| delete space[i] | |
| } | |
| } | |
| { | |
| for (i in space) { | |
| $i = "," | |
| } | |
| gsub(/,+/,",") | |
| }' | |
| writeLines(text, a) | |
| command <- sprintf("awk -f %s %s", a, infile) | |
| system(command, intern = TRUE) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://stackoverflow.com/a/30869273/1270695