简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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