我正在寻找一种有效的方法来删除file1中不存在于bash中的file2中的行:
file1.txt:
file1 <- 'probeset_id sample1 sample2 sample3
AX-2 100 200 180
AX-1 90 180 267
AX-3 80 890 124'
file1 <- read.table(text=file1, header=T)
write.table(file1, "file1.txt", col.names=T, quote=F, row.names=F)file2.txt:
file2 <- 'probeset_id
AX-1
AX-2 '
file2 <- read.table(text=file2, header=T)
write.table(file2, "file2.txt", col.names=F, quote=F, row.names=F)预期产出:
out <- 'probeset_id sample1 sample2 sample3
AX-1 90 180 267
AX-2 100 200 180'
out <- read.table(text=out, header=T)
write.table(out, "out.txt", col.names=T, quote=F, row.names=F)另外一个问题是,file2没有被排序为file1。我试着用:
head -n 1 file1.txt ; grep -f file2.txt file1.txt然而,这需要很长时间。有没有更有效地执行它的想法(真正的文件相当大)?
发布于 2016-01-28 12:13:35
在这种情况下,awk是非常有用的。
awk 'NR==FNR{line[$1]++; next} $1 in line'示例
$ awk 'NR==FNR{line[$1]++; next} $1 in line' file2 file1
probeset_id sample1 sample2 sample3
AX-2 100 200 180
AX-1 90 180 267它做什么?
NR==FNR{line[$1]++; next}将file2中的行保存在关联数组line中(由第一列索引)NR==FNR是正确的,file2。- `NR` Number or records read till now.
- `FNR` Number of records read in the current file.
$1 in line检查file1中的第1列是否已经保存在line中,如果为真,awk将采取打印当前记录的默认操作。https://stackoverflow.com/questions/35061101
复制相似问题