如何用另一文件(数组?)中分配的变量替换一个文件中的字符串

2024-10-03 15:34:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件,我想用一个替换另一个文件中的字符串。第一个(名称.txt)看起来像这样:

S_AA_45_biomass[c]  AA-biomass_c    
S_B10[c]    L-Isoleucine-biomass_c  
S_B11[c]    L-Leucine-biomass_c 
S_B12[c]    L-Lysine-biomass_c  
S_B13[c]    L-Methionine-biomass_c  
S_B14[c]    L-Phenylalanine-biomass_c
S_cpd00322[c]   L-Isoleucine_c  

其中第1列对应于第二个文件中的字符串,第2列是我想将这些字符串更改为的内容。文件2(反应.txt)看起来像这样:

B10_c   L-Isoleucine biomass reaction   S_cpd00322[c]  -> S_B10[c]      0     0.00  1000.00   0.00

我想要的是这样一个输出:

B10_c   L-Isoleucine biomass reaction   L-Isoleucine_c  -> L-Isoleucine-biomass_c       0     0.00  1000.00   0.00

我正试图用sed来替换每个字符串来编写for循环:

for i in `cat Names.txt `; do cat Reactions.txt | grep -F `echo $i | cut -f1` | sed 's/`echo $i | cut -f1`/`echo $i | cut -f2`/' >>output.txt; done

除了因为电影中的特殊角色,这不起作用名称.txt文件,还因为它在将结果写入之前每行只替换一个单词输出.txt,两个文件都超过2000行,因此这不是一个非常有效的方法。我在想一个数组也许是一个可行的方法,但远不能确定这一点。不要太挑剔的方法,只是在一个结果!你知道吗


Tags: 文件方法字符串echotxt名称forsed
1条回答
网友
1楼 · 发布于 2024-10-03 15:34:23

您可以使用这个awk

awk 'FNR==NR {
    a[$1] = $2;
    next
} {
    for (i=1; i<=NF; i++)
       printf (($i in a)? a[$i] : $i) ((i<NF)? OFS : ORS)
}' Names.txt Reactions.txt

B10_c L-Isoleucine biomass reaction L-Isoleucine_c -> L-Isoleucine-biomass_c 0 0.00 1000.00 0.00

相关问题 更多 >