R: Parse a line like a shell command line

Viewed 25

I have a key=value file like follows:

a=foo
b="foo bar"
c="foo \"bar\""
d="foo \'bar\'"

Values appear to be quoted/escaped when there are special characters with a logic similar to the shell. To parse the file into a named vector, the straight way is:

txt <- readLines("dat")
spl <- strsplit(txt, "=")
vec <- setNames(sapply(spl, `[`, 2),
                sapply(spl, `[`, 1))

which gives:

    a               b                       c                     d 
"foo"   "\"foo bar\""   "\"foo \\\"bar\\\"\""   "\"foo \\'bar\\'\"" 

Now, just like for the shell quotes in mkdir "new folder" are not literal, the same is above.
Therefore, I reparse vec with:

prs <- function(el) if(substr(el, 1, 1) == "\"") eval(parse(text= el)) else el
sapply(vec, prs)

That is:

    a           b               c             d 
"foo"   "foo bar"   "foo \"bar\""   "foo 'bar'" 

I wonder if, rather than my naive prs function, there is an established one, perhaps from a library, to parse cli-like lines. What I have found so far, assumes R scripts, where commandArgs() already makes the tokenising task.

0 Answers
Related