Skip to content

Instantly share code, notes, and snippets.

@rpetit3
Created March 18, 2016 18:57
Show Gist options
  • Save rpetit3/ddb85be296cdf46361bc to your computer and use it in GitHub Desktop.
Save rpetit3/ddb85be296cdf46361bc to your computer and use it in GitHub Desktop.
rename-fasta-header.py
#! /usr/bin/env python
"""
Prefix a set of FASTA (STDIN) headers with a given string.
Example run: zcat my_fasta.gz | ./rename-fasta-header.py headers.txt PREFIX
"""
from __future__ import print_function
if __name__ == '__main__':
import sys
import argparse as ap
parser = ap.ArgumentParser(
prog='fastq_cleanup',
conflict_handler='resolve',
description='Prefix a a set of FASTA headers with a given string.')
group1 = parser.add_argument_group('Options', '')
group1.add_argument('header', metavar="LIST_FILE", type=str,
help='A list of headers to search for and prefix.')
group1.add_argument('prefix', metavar="STR", type=str,
help='A string to prefix the fasta headers with.')
args = parser.parse_args()
headers = {}
with open(args.header, 'r') as fh:
for line in fh:
line = '>{0}'.format(line)
headers[line] = True
for line in sys.stdin:
if line in headers:
line = line.replace('>', '>{0}-'.format(args.prefix))
print(line, end="")
@gitanjali0806
Copy link

It is not working

@rpetit3
Copy link
Author

rpetit3 commented Feb 21, 2024

Hi @gitanjali0806, you will need to make sure your headers.txt file matches headers in the FASTA file exactly.

@gitanjali0806
Copy link

gitanjali0806 commented Feb 21, 2024 via email

@gitanjali0806
Copy link

Hi @gitanjali0806, you will need to make sure your headers.txt file matches headers in the FASTA file exactly.

I have checked the name in the header file it matches exactly with the fasta file..
fasta_file
headers_file

i want to replace ">TCONS_00000001 gene=JAJFZO010000001.1_gene_1" with "JAJFZO010000001.1"

@rpetit3
Copy link
Author

rpetit3 commented Feb 22, 2024

Ah, this likely will not be possible with this script, as it doesn't replace anything only adds. So, if the prefix were "MYFASTA", ">TCONS_00000001 gene=JAJFZO010000001.1_gene_1" would become ">MAYFASTA-TCONS_00000001 gene=JAJFZO010000001.1_gene_1"

I wonder if you could just get away with using something like sed

@gitanjali0806
Copy link

gitanjali0806 commented Feb 23, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment