Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created June 26, 2015 02:28
Show Gist options
  • Select an option

  • Save mrdwab/43f59d1d7e6cd373f455 to your computer and use it in GitHub Desktop.

Select an option

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.
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(/,+/,",")
print
}'
writeLines(text, a)
command <- sprintf("awk -f %s %s", a, infile)
system(command, intern = TRUE)
}
@mrdwab

mrdwab commented Mar 9, 2016

Copy link
Copy Markdown
Author

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