Mac OS X下用sed将BLAST XML中OS=后内容全部放入[]的方法
<Hit_def> Modification on macOS The issue with your original sed command is that the character set you used ([A-Za-z\.\-\,\_ ]) doesn't cover special characters like colons, slashes, or parentheses. Plus, relying on a fixed character set isn't flexible for the varied organism names in BLAST outputs.
Here's a robust, two-step sed approach that works with macOS's BSD sed:
sed -E 's/(<Hit_def>.*)OS=/\1[/' input.xml | sed -E 's/( [A-Z]{2}=)/]\1/' > output.xml
How it works:
First
sedcommand: Finds the<Hit_def>tag content and replacesOS=with[, effectively starting the bracket around the organism name.(<Hit_def>.*)captures everything from the start of<Hit_def>up toOS=\1[replaces that captured text plusOS=with the captured text plus[
Second
sedcommand: Locates the first occurrence of a field marker (likeOX=,GN=, etc. — all follow the pattern[A-Z]{2}=) and prepends a]to close the bracket around the organism name.( [A-Z]{2}=)captures the first field marker after the organism name]\1replaces that captured marker with]plus the marker itself
Example test:
For your problematic input line:
<Hit_num>1</Hit_num> <Hit_id>TR:V4U0L5_9ROSI</Hit_id> <Hit_def>gnl|V4U0L5| Uncharacterized protein OS=Yersinia enterocolitica serotype O:8 / biotype 1B (strain NCTC 13174 / 8081) OX=393305 GN=CICLE_v10008136mg PE=4 SV=1</Hit_def> <Hit_accession>TR:V4U0L5_9ROSI</Hit_accession> <Hit_len>388</Hit_len>
This command will output:
<Hit_num>1</Hit_num> <Hit_id>TR:V4U0L5_9ROSI</Hit_id> <Hit_def>gnl|V4U0L5| Uncharacterized protein [Yersinia enterocolitica serotype O:8 / biotype 1B (strain NCTC 13174 / 8081)] OX=393305 GN=CICLE_v10008136mg PE=4 SV=1</Hit_def> <Hit_accession>TR:V4U0L5_9ROSI</Hit_accession> <Hit_len>388</Hit_len>
This method handles all special characters in organism names because it doesn't rely on matching specific characters — it just targets the start (OS=) and end (first field marker) of the organism name segment.
内容的提问来源于stack exchange,提问作者adee1212

