You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为非注释行的VCF文件添加chr前缀的sed命令优化需求

Add 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 .bak to create a backup of the original file (e.g., sed -i.bak ... will leave your_vcf_file.vcf.bak as 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 inserts chr at 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:02:54