我有一个像这样带有制表符分隔符的文件:
Chr1 mak gene 120221 120946 . + . ID=spa-h0003.02;Name=spa-h0003.02
Chr1 mak mRNA 120221 120946 . + . ID=spa-cap_Chr1_00M;Parent=spa-h0003.02;Name=spa-cap_Chr1_00M
Chr1 mak exon 120221 120946 . + . Parent=spa-cap_Chr1_00M
Chr1 mak gene 18546165 18546939 . + . ID=spa-h0004.02;Name=spa-h0004.02
Chr1 mak mRNA 18546165 18546939 . + . ID=spa-cap_Chr1_18;Parent=spa-h0004.02;Name=spa-cap_Chr1_18
Chr1 mak exon 18546165 18546504 . + . Parent=spa-cap_Chr1_18
Chr1 mak exon 18546791 18546939 . + . Parent=spa-cap_Chr1_18
仅当第三列具有“基因”时,我才想替换不同的字符串。但是第九列上的字符串应该根据第二个文件中存在的信息进行替换,如下所示(带有制表符):
spa-h0003.02 spa-cap_Chr1_00M
spa-h0004.02 spa-cap_Chr1_18
我不知道该怎么做。我在想类似的事情(XX应该是第二个文件中的信息?):
cat file | awk '$3 == "gene" && $9 == "spa-" {$9 = "XX"} {print}'
但是我如何使用第二个文件中的信息呢?或许:
while read n k; do sed -i 's/$n/$k/g' file1; done < fileA
答案1
假设file1
包含要替换的文本,file2
包含替换文本,并且您可以依靠在ID=
两者之间执行查找,您可以使用这个(我猜更流行)awk 脚本:
awk -F'\t' '
NR==FNR{
a[$1]=$2 # fills the array a with the replacement text
next
}
$3=="gene"{ # check only lines with 'gene'
id=gensub("ID=([^;]*);.*","\\1",1,$9); # extract the id string
if(id in a) # if the id is part of the array a
gsub(id,a[id]) # replace it
}
1 # print the line
' file2 file1
答案2
一个不受欢迎的选择:Tcl。 Tcl 有一个很好的string map
命令可以完成确切地这。不幸的是,Tcl 并不是真正为 Perl 风格的单行代码构建的。
echo '
# read the mapping file into a list
set fh [open "mapping" r]
set content [read $fh]
close $fh
set mapping [regexp -all -inline {\S+} $content]
# read the contents of the data file
# and apply mapping to field 9 when field 3 is "gene"
set fh [open "file" r]
while {[gets $fh line] != -1} {
set fields [split $line \t]
if {[lindex $fields 2] eq "gene"} {
lset fields 8 [string map $mapping [lindex $fields 8]]
}
puts [join $fields \t]
}
close $fh
' | tclsh
使用 awk,我会写:
awk -F'\t' -v OFS='\t' '
NR == FNR {repl[$1]= $2; next}
$3 == "gene" {
for (seek in repl)
while ((idx = index($9, seek)) > 0)
$9 = substr($9, 1, idx-1) repl[seek] substr($9, idx + length(seek))
}
{print}
' mapping file