2

I want to read the last line of a txt file by readLines in R, how can I achieve this?

con<-file("test.txt","r")
line<-readLines(con,n=-1)
cat(line,"\n")
close(con)

the text file is as followed

3B1CHLH_PI210.PV       07-MAY-15 10:33:52.5       173.944       Good
3B1CHLH_PI210.PV       07-MAY-15 10:34:29.0       173.379       Good
3B1CHLH_PI210.PV       07-MAY-15 10:35:25.6       172.890       Good
3B1CHLH_PI210.PV       07-MAY-15 10:35:58.3       173.009       Good
3B1CHLH_PI210.PV       07-MAY-15 10:36:50.9       173.677       Good
3B1CHLH_PI210.PV       07-MAY-15 10:37:18.6       173.069       Good
3B1CHLH_PI210.PV       07-MAY-15 10:37:49.2       173.408       Good
3B1CHLH_PI210.PV       07-MAY-15 10:38:39.6       173.445       Good
3B1CHLH_PI210.PV       07-MAY-15 10:39:12.5       173.445       Good

I can only get all the lines, but I only want to read the last line, is there any way in R like the fseek in C

Cheng
  • 193
  • 3
  • 10
  • 2
    Try `readLines(textConnection(system("tail -1 text.txt", intern=TRUE)))` – akrun Jun 21 '15 at 16:40
  • 1
    Similar to @akrun's suggestion, if you are on a Unix-like machine you can use `sed` to deal with the extra `"`s: `row <- system("tail -n 1 ~/tmp/tmpfile.csv | sed -E 's/\"+//g'", intern = TRUE); strsplit(row, ",", fixed = TRUE)[[1]]` – nrussell Jun 21 '15 at 16:49
  • @Akrun, its probably worth adding your comment (and mrussels) as another answer to the question identifed by MrF - its a nice alt – user20650 Jun 21 '15 at 18:24
  • @user20650 But, in the link, it is for the windows case, I am using `linux`. Does it work with `windows`? – akrun Jun 21 '15 at 18:26
  • Yes youre right: `tail` is for *nix. Perhaps a Windows alternative is to use `system('find /v /c "/@/@/@!!??" text.txt', intern=TRUE)` to count the number of lines ([from here](http://www.computerhope.com/issues/ch000820.htm)), similar to the second `scan` option in the other question, except it can be automated, as it actually returns the number of rows. You could then use skip and nrow in R. – user20650 Jun 21 '15 at 18:55

0 Answers0