Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the first line from a text file?

Tags:

r

I have a text file that I read like this:

file=read.table("file.txt",skip="1",sep="")

The first line of this text file contains information about the file then it is followed by the observations.

I want to extract the first line and write it out to a new text file.

like image 705
temor Avatar asked Oct 10 '15 08:10

temor


2 Answers

To read the first line of a file, you can do:

con <- file("file.txt","r")
first_line <- readLines(con,n=1)
close(con)

To write it out, there are many options. Here is one:

cat(first_line,file="first_line.txt")
like image 154
scoa Avatar answered Nov 20 '22 06:11

scoa


Another way to do it is to read it with read.table() like this:

read.table(file = 'file.txt',header = F,nrows = 1)

This is a simple way to do it, and you can get your data separated into columns which makes it easier to work with.

like image 31
Santiago I. Hurtado Avatar answered Nov 20 '22 08:11

Santiago I. Hurtado