这可能不是自我解释,但是,我正在尝试在比较两个文件后创建一个文件。
FILE1.TXT
GO:0016020
GO:0043065
GO:0003713
GO:0007090
File2.txt
Gene1 "GO:0016020,GO:0003713"
Gene2 "GO:0016020,GO:0003713,GO:0007090"
Gene3 "GO:0003713"
Output.txt的
GO:0016020 Gene1
GO:0016020 Gene2
GO:0003713 Gene1
GO:0003713 Gene2
GO:0003713 Gene3
GO:0007090 Gene2
基本上我想打印file1加上找到第一列的第一列。
我试过这段代码:
awk 'FNR==NR{a[FNR]=$1; next}{print a[FNR],$1}' File1.txt File2.txt > output.txt
output.txt如下所示:
GO:0016020 Gene1
GO:0043065 Gene2
GO:0003713 Gene3
我只报告了一个实例。
有人能帮助我吗
答案 0 :(得分:4)
使用GNU awk 4. *表示真正的多维数组:
$ cat tst.awk
BEGIN { FS="[ \"]+" }
NR==FNR {
split($2,a,/,/)
for (i=1; i in a; i++) {
genes[a[i]][$1]
}
next
}
{
if ($0 in genes) {
for (gene in genes[$0]) {
print $0, gene
}
}
}
$ awk -f tst.awk file2 file1
GO:0016020 Gene1
GO:0016020 Gene2
GO:0003713 Gene1
GO:0003713 Gene2
GO:0003713 Gene3
GO:0007090 Gene2
答案 1 :(得分:3)
没有多维数组的替代awk
解决方案
$ awk 'NR==FNR{a[$2]=$1;next} {for(r in a) if(r~$1) print $1,a[r]}' file2 file1
GO:0016020 Gene2
GO:0016020 Gene1
GO:0003713 Gene2
GO:0003713 Gene1
GO:0003713 Gene3
GO:0007090 Gene2
答案 2 :(得分:1)
或者你可以在经过一些操作之后使用Unix“join”。加入还需要排序文件:
sort file1.txt > file1.sort.txt
cat file2.txt|tr -d \"|tr , " "|awk '{for(i=2;i<=NF;++i)print $i,$1}'|sort|join - file1.sort.txt
答案 3 :(得分:0)
我知道这个问题是关于awk的,但我已经在php中开发了一个有效的解决方案
<?php
//Read File1.txt to a varaiable
$file1 = file_get_contents("File1.txt");
//Read File2.txt to a varaiable
$file2 = file_get_contents("File2.txt");
//Creates an empty array to hold the Output
$output = array();
//matches all genes on File1.txt
preg_match_all('/GO:\d+/i', $file1, $matches, PREG_PATTERN_ORDER);
//Loop results of genes on File1.txt
foreach($matches[0] as $gene){
//match gene number for this specific gene in File2
preg_match_all("/(Gene\d+).*?$gene/i", $file2, $matches2, PREG_PATTERN_ORDER);
//Loop matches of File2.txt
for ($i = 0; $i < count($matches2[1]); $i++) {
//add to array output
array_push($output, $gene." ".$matches2[1][$i]);
}
}
//unique genes
$output = array_unique($output);
//output the unique genes to Output.txt
foreach($output as $sortedGene){
file_put_contents('Output.txt',$sortedGene."\n", FILE_APPEND);
}
/*
GO:0016020 Gene1
GO:0016020 Gene2
GO:0003713 Gene1
GO:0003713 Gene2
GO:0003713 Gene3
GO:0007090 Gene2
*/