1

I have a fasta file contained ~28000 sequence. I want to replace header of these sequences by a list of lines in another file. Example:

File 1:

sp|B7UM99|TIR_ECO27
MPIGNLGNNVNGNHLIPPAPP.....
sp|P0ACF8|HNS_ECOLI
MSEALKILNNIRTLRAQ........
sp|P24232|HMP_ECOLI
MLDAQTIATVKATIPLLVET..........

File 2:

sp|B7UM99|TIR_ECO27OS=Escherichia coli
sp|P0ACF8|HNS_ECOLI=Human
sp|P24232|HMP_ECOLI=Flavohemoprotein

Desired Output:

sp|B7UM99|TIR_ECO27OS=Escherichia coli
MPIGNLGNNVNGNHLIPPAPP.....
sp|P0ACF8|HNS_ECOLI=Human
MSEALKILNNIRTLRAQ........
sp|P24232|HMP_ECOLI=Flavohemoprotein
MLDAQTIATVKATIPLLVET..........
0

Perhaps, the script below is what you need:

#!/bin/bash

# Save the good lines
awk '{if($0 !~ "^sp")print > "result_1" }' < file_1
awk '{if($0 ~ "^sp")print > "result_2" }' < file_2

# Get number of lines in result_1 ( == nl in result_2 )
nl_file=$(wc -l result_1|cut -d' ' -f1)

# Prepare sorting of these files preceded by a number
seq 2 2 $(( ${nl_file} * 2 )) > numbered_file_1
seq 1 2 $(( ${nl_file} * 2 )) > numbered_file_2

# paste content of numbered_file_* and result_* side by side
paste -d ' ' numbered_file_1 result_1 > mergedfiles
paste -d ' ' numbered_file_2 result_2 >> mergedfiles

sort -n mergedfiles | sed 's/^[[:digit:]]\s\+//g'
0

Assuming that all lines in file 2 begin with sp|, and that the sp| lines in file 1 don't contain any regexp characters that would confuse grep:

$ cat file.sh
while read line
do
        case "${line}" in
        sp\|*)
                grep "^$line" file2 || printf '%s\n' "$line"
        ;;
        *)
                printf '%s\n' "$line"
        esac
done
$ sh file.sh < file1
sp|B7UM99|TIR_ECO27OS=Escherichia coli
MPIGNLGNNVNGNHLIPPAPP.....
sp|P0ACF8|HNS_ECOLI=Human
MSEALKILNNIRTLRAQ........
sp|P24232|HMP_ECOLI=Flavohemoprotein
MLDAQTIATVKATIPLLVET..........

I would have liked to use the -F option to grep, but I felt that it was more important to require that the match be anchored to beginning-of-line.

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.