0

I have a text file with multiple paragraphs. Each paragraph has headers with spaces. I want to replace the spaces of the text found between [ and :, with _ . Here is an excerpt of the text from the file I am talking about

[Candidatus Protochlamydia amoebophila UWE25: NC_005861]
MNQRTGILLVNLGTPKTPRPKDVYRYLNEFLTDGRVIDLPWLKRQLLVRC
IIVPFRYKQSSMLYQKLWTAEGSPLLVHGIAVQTKLQMILGESFQVELAM


[Gluconobacter oxydans 621H: NC_006677]
MAFLHKTPRIAPPPEGRTGILLINLGTPDDTGYFSVRRYLSEFLSDRRVI
ESPPLIWQPILQSIILTKRPFASGANYARIWHKEENASPLRVYTRRQAEG

I need it to be changed into this:

[Candidatus_Protochlamydia_amoebophila_UWE25: NC_005861]
MNQRTGILLVNLGTPKTPRPKDVYRYLNEFLTDGRVIDLPWLKRQLLVRC
IIVPFRYKQSSMLYQKLWTAEGSPLLVHGIAVQTKLQMILGESFQVELAM


[Gluconobacter_oxydans_621H: NC_006677]
MAFLHKTPRIAPPPEGRTGILLINLGTPDDTGYFSVRRYLSEFLSDRRVI
ESPPLIWQPILQSIILTKRPFASGANYARIWHKEENASPLRVYTRRQAEG

I've tried

$ sed -e 's/\s\+/_/g' input.txt > output.txt

but that replaces all spaces with _ How can I set a limitation on this command?

0

One way would be to use a loop, replacing spaces one at a time until there are no more before the first colon:

$ sed -e :a -e '/[^:]* [^:]*:/s/ /_/;ta' input.txt 
[Candidatus_Protochlamydia_amoebophila_UWE25: NC_005861]
MNQRTGILLVNLGTPKTPRPKDVYRYLNEFLTDGRVIDLPWLKRQLLVRC
IIVPFRYKQSSMLYQKLWTAEGSPLLVHGIAVQTKLQMILGESFQVELAM


[Gluconobacter_oxydans_621H: NC_006677]
MAFLHKTPRIAPPPEGRTGILLINLGTPDDTGYFSVRRYLSEFLSDRRVI
ESPPLIWQPILQSIILTKRPFASGANYARIWHKEENASPLRVYTRRQAEG

A more KISS approach might be to replace all spaces - and then re-replace the one after the colon:

sed -e 's/\s\+/_/g' -e 's/:_/: /' input.txt

If Perl is an option, you could use negative lookbehind to only replace those instances that are not preceded by a colon:

perl -pe 's/(?<!:) /_/g' input.txt
| improve this answer | |
  • The first option worked great! Thank you! – Weerthy Jan 24 at 3:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.