[英]How to replace a string in one file with a variable assigned from another file (array?)
I have two files and I would like to use one to replace strings in another file. 我有两个文件,我想用一个替换另一个文件中的字符串。 The first (Names.txt) looks like this: 第一个(Names.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
where column 1 corresponds to the strings in the second file and column 2 is what I would like to change those strings to. 其中列1对应于第二个文件中的字符串,列2是我想将这些字符串更改为的字符串。 File 2 (Reactions.txt) looks like this: 文件2(Reactions.txt)如下所示:
B10_c L-Isoleucine biomass reaction S_cpd00322[c] -> S_B10[c] 0 0.00 1000.00 0.00
and what I want is an output that looks like this: 我想要的是一个看起来像这样的输出:
B10_c L-Isoleucine biomass reaction L-Isoleucine_c -> L-Isoleucine-biomass_c 0 0.00 1000.00 0.00
I was trying to write a for loop using sed to replace each string: 我试图用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
Apart from the fact that this doesn't work because of the special characters in the Names.txt file and also because it replaces only one word on each line before writing the results to output.txt, both files are over 2000 lines long so this isn't a very efficient approach. 除了由于Names.txt文件中的特殊字符而导致此操作不起作用,以及由于在将结果写入output.txt之前每行仅替换一个单词之外,这两个文件的长度都超过2000行,因此这不是一个非常有效的方法。 I was thinking an array might be the way to go but far from certain about that. 我当时在想使用数组可能是可行的方法,但还远不能确定。 Not too fussy about the approach, just after a result! 结果之后,不要太挑剔!
You can use this awk
: 您可以使用以下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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.