问题
This is a little frustrating, and I'm sure there's an easy answer.
history(max.show=N)
will display N lines of history on to the terminal. savehistory(file)
will save a number of lines of history to a file, depending on some environment variable. What I would like to do is
savehistory(file, max.show=N)
To do this in one line instead of having to copy or trawl through a history file for the lines I want would make things much easier.
Is there a quick function/way to save a specified number of lines to a specified file?
回答1:
I think your best bet is to abuse the history function:
history2file <- function (fname, max.show = 25, reverse = FALSE, pattern, ...)
{
## Special version of history() which dumps its result to 'fname'
file1 <- tempfile("Rrawhist")
savehistory(file1)
rawhist <- readLines(file1)
unlink(file1)
if (!missing(pattern))
rawhist <- unique(grep(pattern, rawhist, value = TRUE,
...))
nlines <- length(rawhist)
if (nlines) {
inds <- max(1, nlines - max.show):nlines
if (reverse)
inds <- rev(inds)
}
else inds <- integer()
writeLines(rawhist[inds], fname)
}
history2file("/tmp/bla")
I would however stimulate you to start working in script files directly, and not do stuff on the command line and then later try to piece a script together.
来源:https://stackoverflow.com/questions/9806333/how-can-i-save-a-specified-number-of-lines-from-rs-history-to-a-file