简体   繁体   English

忽略N个匹配项后sed或awk替换

[英]sed or awk replace after ignoring N matches

I have a repetitive text, I want to carefully replace one label with another several times, I don mind repeating sed awk or another method. 我有一个重复的文本,我想用另一个标签仔细地替换另一个标签,我不介意重复sed awk或另一种方法。 Therefore I would want to first replace the first two matches, then after the first 4, 6, etc. I don't want a for , I just need something like the code below, I want to skip the first two matches and then increase that number. 因此,我想先替换前两个匹配项,然后替换前4、6等。我不需要for ,我只需要下面的代码,我想跳过前两个匹配项,然后增加该号码。

sed 's/foo/bar/2g' fileX 
awk '{ sub(/foo/,"bar"); print }' fileX

here is an example. 这是一个例子。 Two occurrences per line 每行两次

blastx -q specie.fa -db pep -num 6 -max 1 -o 6 > specie.x.outfmt6
blastp -q specie.pep -db pep -num 6 -max 1 -o 6 > specie.p.outfmt6
blastx -q specie.fa -db pep -num 6 -max 1 -o 6 > specie.x.outfmt6
blastp -q specie.pep -db pep -num 6 -max 1 -o 6 > specie.p.outfmt6

Desired output 所需的输出

blastx -q dog.fa -db pep -num 6 -max 1 -o 6 > dog.x.outfmt6
blastp -q dog.pep -db pep -num 6 -max 1 -o 6 > dog.p.outfmt6
blastx -q worm.fa -db pep -num 6 -max 1 -o 6 > worm.x.outfmt6
blastp -q worm.pep -db pep -num 6 -max 1 -o 6 > worm.p.outfmt6

Is this what you're trying to do? 这是您要做什么?

$ awk -v animals='monkey worm dog' 'BEGIN{split(animals,a)} NR%2{c++} {$NF=a[c]} 1' file
here some text -t monkey
and then do something -t monkey
here some text -t worm
and then do something -t worm
here some text -t dog
and then do something -t dog

Given your new sample input/output maybe this is what you want: 给定新的示例输入/输出,也许这是您想要的:

$ awk -v animals='dog worm' 'BEGIN{split(animals,a)} NR%2{c++} {gsub(/specie/,a[c])} 1' file
blastx -q dog.fa -db pep -num 6 -max 1 -o 6 > dog.x.outfmt6
blastp -q dog.pep -db pep -num 6 -max 1 -o 6 > dog.p.outfmt6
blastx -q worm.fa -db pep -num 6 -max 1 -o 6 > worm.x.outfmt6
blastp -q worm.pep -db pep -num 6 -max 1 -o 6 > worm.p.outfmt6

Since you didn't include any regexp characters or backreference characters or partial match cases in your sample input/output (eg if the word species appeared somewhere and should NOT be changed) I assume they can't happen and so we don't need the script to guard against them. 由于您在示例输入/输出中没有包含任何正则表达式字符或后向引用字符或部分匹配用例(例如,如果单词species出现在某个地方并且不应更改),我认为它们不会发生,因此我们不需要该脚本,以防止他们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM