如何用awk/sed在GTF文件末尾追加列5与列4的差值?
Let's get this sorted out—your original awk command was replacing an existing column instead of appending the new value, which is why it didn't work as expected. Here's how to fix it:
The Correct Awk Command
awk 'NR>=6 {$0 = $0 " " $5 - $4} 1' gencode.gtf > output.txt
Breakdown of the Command:
NR>=6: Targets all lines starting from the 6th row (skipping your 5-line header).$0 = $0 " " $5 - $4: Takes the entire existing line ($0), adds a space separator, then appends the result of subtracting column 4 from column 5. This modifies the line to include your new value at the end instead of overwriting an existing column.1: A shorthand in awk that means "print the current line". For lines 1-5, this just prints the original header; for lines 6+, it prints the modified line with the appended difference.
Why Your Original Command Failed
Your initial command awk 'NR>=6 {$10=$5-$4} 1' was overwriting the 10th field (which in your example is gene_id) with the calculation result. GTF files have a fixed structure where each field serves a specific purpose, so replacing an existing field breaks the file format—we need to add a new field instead.
Example Output
For your sample line:
chr1 HAVANA gene 11869 14409 . + . gene_id "ENSG00000223972.5"; ...
The command will produce:
chr1 HAVANA gene 11869 14409 . + . gene_id "ENSG00000223972.5"; ... 2540
Alternative (More Explicit) Version
If you prefer more readable code, this does the exact same thing:
awk '{ if (NR >= 6) { print $0, $5 - $4 } else { print $0 } }' gencode.gtf > output.txt
内容的提问来源于stack exchange,提问作者Gawain

