2013-03-12 16 views
0

我是unix的新手,我正在嘗試學習基礎知識。 我有一個製表符分隔的文件。我想提取以「txGN =」模式開頭的單元格,並將它們打印在相應行中的新列中。這些單元格位於不同的列中。所有行的列數都不相同。這些值出現在大多數行中,但不是全部。如何從位於不同列的特定模式開始使用unix或R提取單元格

這是文件的外觀:

chr1 880942 taPN=-1 taWT=3  txGN=SAMD11 txID=uc001abw FUNC=nonsyn 
chr1 894573 txDN=-3 txGN=NOC2L txID=uc003 intronic 
chr1 10626 txDN=-9 txID=uc2  txST=+ 

非常感謝您

+0

應提供所需輸出的示例。 – igelkott 2013-03-12 18:19:57

回答

0

取決於「unix」的含義,但如果包含基於Unix系統的命令,那麼簡單的Perl腳本怎麼樣?應用下到文件

perl -ne 'print /txGN=([^\s]+)/ ? "$1\t$_" : "\t$_";' your-file 

得到

SAMD11 chr1 880942 taPN=-1  taWT=3  txGN=SAMD11 
NOC2L chr1 894573 txDN=-655 txGN=NOC2L txID=uc001aby.3 
     chr1 1062638 txDN=-9758 txID=uc2  txST=+ 

小重寫可能在其它地方的新列。

+0

非常感謝你。它很棒! – user2162153 2013-03-13 02:51:38

+0

太棒了。請標記爲已解決。 – igelkott 2013-03-13 07:28:33

1
#count maximum number of columns in the "file" 
maxcol <- max(count.fields("D:/file.txt")) 

x <- read.table("D:/file.txt",as.is=TRUE,fill=TRUE,col.names=1:maxcol) 
x[x==""]<-NA 
indices<-which(substr(as.matrix(x),start=1,stop=5)=="txGN=",arr.ind=TRUE) 

x<-cbind(x,NA) 
for(i in 1:nrow(indices)){ 
    na1<-which(is.na(x[indices[i,1],]))[1] 
    x[indices[i,1],na1]<-x[indices[i,1],indices[i,2]] 
} 
x 
    X1  X2  X3   X4   X5   X6   X7   NA 
1 chr1 880942 taPN=-1  taWT=3 txGN=SAMD11 txID=uc001abw FUNC=nonsyn txGN=SAMD11 
2 chr1 894573 txDN=-3 txGN=NOC2L txID=uc003  intronic txGN=NOC2L  <NA> 
3 chr1 10626 txDN=-9 txID=uc2  txST=+   <NA>  <NA>  <NA> 

#If you want to "remove" NA's: 
x[is.na(x)]<-"" 

編輯:

這裏是不創建R中的數據幀的一個版本(以以減少內存需求),而是將結果附加到新文件中:

maxcol <- max(count.fields("D:/file.txt")) 
maxrow <- length(readLines("D:/file.txt")) 
# bit inefficient, we read the whole file to get the number of lines 

stepsize<-50 # how many lines are read at once 
k<-0 
while(TRUE){ 
    if((k+1)*stepsize > maxrow){ 
    x <- read.table("D:/file.txt",as.is=TRUE,fill=TRUE,col.names=1:maxcol, 
        skip=k*stepsize,nrow=maxrow-k*stepsize+1) 
    } else x <- read.table("D:/file.txt",as.is=TRUE,fill=TRUE, 
          col.names=1:maxcol, skip=k*stepsize,nrow=stepsize) 

    if(nrow(x)==0) break #end loop when finished 
    x[x==""]<-NA 
    indices<-which(substr(as.matrix(x),start=1,stop=5)=="txGN=",arr.ind=TRUE) 
    x<-cbind(x,NA) 
    for(i in 1:nrow(indices)){ 
    na1<-which(is.na(x[indices[i,1],]))[1] 
    x[indices[i,1],na1]<-x[indices[i,1],indices[i,2]] 
    } 
    # New stuff, change sep and eol if needed 
    write.table(x, file = "D:/filenew.txt", append = TRUE, quote = FALSE, 
      sep = " ", eol = "\n", na = "",row.names = FALSE, col.names = FALSE) 
    k<-k+1 
} 

read.table("D:/filenew.txt",as.is=TRUE,fill=TRUE,col.names=1:(maxcol+1)) 
+0

非常感謝您的回覆。我忘了說所有行的列數不相同,並且單元格內的字符數不同 – user2162153 2013-03-12 18:05:59

+0

單元格中是否有不同數量的字符並不重要if前5個字符是可以包含想要的字符串的字符。但第二個問題有點棘手.. – 2013-03-12 18:08:12

+0

謝謝。另外,我想將提取的值打印到相應行內的新列中。 – user2162153 2013-03-12 18:12:23

相關問題