This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Replace multiple text with corresponding text

Hi,

I run an analysis and the software replaced the bacteria name with codes, and I have txt file as below:

Order   Original Name   Code
1   Allostreptomyces_psammosilenae_DSM_42178    S1_f1
2   Embleya_hyalina_NBRC_13850  S2_f2
3   Embleya_scabrispora_DSM_41855   S3_f3

Because the analysis involved few hundreds bacteria, it would be difficult to replace it one by one in the output txt file. May I know any method for me replace the code back to my bacteria original name? Thanks in advance.

Best regards,

Felix

replacement text

1 answer

This is a perfect task for sed.

I would suggest modifying the file in to a set of sed commands. Assume your input above is called subs.txt:

awk 'BEGIN {OFS=","} {print $3, $2}' subs.txt | tail -n+2 | sed -e "s|^|s\/|" -e "s|,|\/|" -e "s|$|\/g|" > changes.sed

Given your input, this will create:

s/S1_f1/Allostreptomyces_psammosilenae_DSM_42178/g
s/S2_f2/Embleya_hyalina_NBRC_13850/g
s/S3_f3/Embleya_scabrispora_DSM_41855/g

You can then feed this in as a sed script to alter your original file:

sed -f changes.sed file_to_be_changed.txt

Hi, the changes.sed file is empty. Anyway I am using Macbook, I have also tried using gawk and gsed but the changes.sed file still empty.

Mac implements sed etc slightly differently. It may also do the same for awk. Try building the pipe up part by part.

I'm afraid that's not enough information for me to be able to tell you why it isn't working

Hi, I generated the changes.sed file using excel and save as .txt file as below:

s/S1_f1/Allostreptomyces_psammosilenae_DSM_42178/g
s/S2_f2/Embleya_hyalina_NBRC_13850/g
s/S3_f3/Embleya_scabrispora_DSM_41855/g

But when run the second command I got error as below:

sed: file changes.txt line 1: unknown option to `s'

Any suggestion?

Make sure you are using GNU sed as distributed in coreutils.

I have changed my command to gsed, but result remain the same.

It may be due to you producing the file with Excel. How did you export the file? Any invisible characters will break this.

I saved the file as tab delimitated text file.

OK, so how did you make the file you showed above? did you use the sed commands I gave you on the tab-separated file?

Sorry, I don't know why the command is not working on my side. But still, thanks for your sed command, I manually run all the sed command one by one using && in the terminal.

Log in to answer this question.