[R] how to locate specific line?

William Dunlap wdun|@p @end|ng |rom t|bco@com
Fri Jul 27 16:38:11 CEST 2018


If Sys.which("grep") says that grep is available then system("grep -n ...")
will do it.

> cat(c("One","Two","Three","Four"),sep="\n",file=tf<-tempfile())
> system(paste("grep --line-number", shQuote("^T"), shQuote(tf)),
intern=TRUE)
[1] "2:Two"   "3:Three"
> as.integer(sub(":.*$", "", .Last.value))
[1] 2 3

grep is always on Unix-like systems and is in the Rtools and Cygwin
distributions on Windows.  I don't know how standard the '-n' (aka
--line-number) flag is.



Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Fri, Jul 27, 2018 at 1:13 AM, Jinsong Zhao <jszhao using yeah.net> wrote:

> Hi there,
>
> I have a large/huge text file. I need to locate a line in the file with a
> specific string, for example, "Data Points". Now, I use the following code
> to do:
>
> df <- readLines(file)
> l <- grep("Data Points", df)
>
> However, in this case, the file will be read throughout into R. When the
> file is huge, it will cost much memory and time.
>
> Is there any more elegant way to do that? Thanks.
>
> Best,
> Jinsong
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posti
> ng-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]




More information about the R-help mailing list