为非注释行的VCF文件添加chr前缀的sed命令优化需求
chr Prefix to Non-## Lines in VCF (Directly Overwrite with sed) Got it, let's tackle this VCF formatting task cleanly! You mentioned originally using a grep + sed combo to add the chr prefix to lines that don't start with ##, but want a single sed command that overwrites the original file directly—here's how to do it right.
The Problem with the Grep+Sed Combo
Your initial approach might look something like this:
grep -v "^##" input.vcf | sed 's/^/chr/' > temp.vcf && mv temp.vcf input.vcf
This works, but it requires a temporary file and extra steps. We can condense this into a single sed command that edits the file in-place.
The In-Place Sed Solution
For GNU sed (Linux systems):
sed -i '/^##/! s/^/chr/' your_vcf_file.vcf
For BSD sed (macOS, BSD systems):
You need to add an empty string argument to -i (to avoid creating a backup file by default):
sed -i '' '/^##/! s/^/chr/' your_vcf_file.vcf
What This Command Does
Let's break it down:
-i: Tells sed to edit the file in-place (overwrite the original). For GNU sed, you can add a suffix like.bakto create a backup of the original file (e.g.,sed -i.bak ...will leaveyour_vcf_file.vcf.bakas the unmodified original)./^##/!: This is a sed address that matches all lines NOT starting with##(the!negates the match).s/^/chr/: The substitution command that insertschrat the start (^) of the matched lines.
Example Test
Suppose your VCF looks like this:
##fileformat=VCFv4.2 ##FILTER=<ID=PASS,Description="All filters passed"> 1 1000000 rs12345 A T . PASS . GT:AD:DP 2 2000000 rs67890 G C . PASS . GT:AD:DP
After running the sed command, it will become:
##fileformat=VCFv4.2 ##FILTER=<ID=PASS,Description="All filters passed"> chr1 1000000 rs12345 A T . PASS . GT:AD:DP chr2 2000000 rs67890 G C . PASS . GT:AD:DP
Pro Tip: Always Backup First
If you're worried about accidentally messing up the original file, use the backup suffix with -i:
# GNU sed sed -i.bak '/^##/! s/^/chr/' your_vcf_file.vcf # BSD sed sed -i.bak '' '/^##/! s/^/chr/' your_vcf_file.vcf
This will create a your_vcf_file.vcf.bak backup of the original, so you can revert if needed.
内容的提问来源于stack exchange,提问作者Andrea Spinelli

