<p>If you really just want the start and end positions of all genes in a list of genes from <a href="ftp://ftp.ensembl.org/pub/current_gtf/homo_sapiens/Homo_sapiens.GRCh38.93.gtf.gz" rel="nofollow noreferrer">Homo_sapiens.GRCh38.93.gtf.gz</a>, you could do this in <code>awk</code>. For example, if your list of genes is:</p>

<pre><code>$ cat genes
ENSG00000131482
ENSG00000223972
ENSG00000228794
ENSG00000187961
</code></pre>

<p>You can do:</p>

<pre><code>$ awk '{ 
        if(NR==FNR){
            wantedGenes[$1]++ 
        } 
        else{
            if($3=="gene"){
                gsub(/";*/,"",$10); 
                if($10 in wantedGenes){
                    print $10,$4,$5
                } 
            }
        }
      }' genes Homo_sapiens.GRCh38.93.gtf 
ENSG00000223972 11869 14409
ENSG00000228794 825138 859446
ENSG00000187961 960587 965715
ENSG00000131482 42900797 42913369
</code></pre>

<h3>Explanation:</h3>

<ul>
<li><code>if(NR==FNR){ wantedGenes[$1]++ }</code> : <code>NR</code> is the input line number and <code>FNR</code> is the current line number of <em>this</em> input file. The two are only equal while reading the first file. So, if this is the first file, save the first field of each line (the gene name) in the array <code>wantedGenes</code>.</li>
<li><code>if($3=="gene"){</code> : if this line is a 'gene' entry.</li>
<li><code>gsub(/";*/,"",$10);</code> : the gene names in the GTF file are quoted and have an <code>;</code> after the quote. For example: <code>"ENSG00000187961";</code>. Since we don't have this in the list, we need to remove it so we can match the gene name. This <code>gsub</code> command will remove all <code>"</code> followed by 0 or more <code>;</code> (the <code>;*</code> means 0 or more occurrences of <code>;</code>) from the 10th field of each line. So, it will replace <code>"ENSG00000187961";</code> with <code>ENSG00000187961</code>.</li>
<li><code>if($10 in wantedGenes){print $10,$4,$5}</code> : if the 10th field (the modified gene name from above) is in the <code>wantedGenes</code> array, then print the 10th field (the gene name), the 4th (start) and the 5th field (end).</li>
</ul>

<p>You can easily modify this to print the length instead of the start and end positions:</p>

<pre><code>$ awk '{ 
        if(NR==FNR){
            wantedGenes[$1]++ 
        } 
        else{
            if($3=="gene"){
                gsub(/";*/,"",$10); 
                if($10 in wantedGenes){
                    print $10,$5-$4
                } 
            }
        }
      }' genes Homo_sapiens.GRCh38.93.gtf 
ENSG00000223972 2540
ENSG00000228794 34308
ENSG00000187961 5128
ENSG00000131482 12572
</code></pre>

<p>As requested in chat, here's a python version of the same thing:</p>

<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3
import re
import sys

wantedGenes = []
with open(sys.argv[1], mode='r') as f:
    wantedGenes = f.readlines()

wantedGenes = [ x.rstrip() for x in wantedGenes]

print('# Gene\tstart\tend\tlength')
with open(sys.argv[2], mode='r') as f:
    for line in f:
        if not line.startswith('#'): 
            fields = line.split('\t')
            annotations = fields[8].split(' ')
            geneName = re.sub('[";]', '', annotations[1])
            if geneName in wantedGenes and fields[2] == 'gene':
                print('%s\t%s\t%s\t%d' %
                      (geneName, fields[3],fields[4],
                       int( int(fields[4]) - int(fields[3]) )
                      ))
</code></pre>

<p>Save the file as <code>foo.py</code> and run with the file names as arguments:</p>

<pre><code>python foo.py geneList.txt Homo_sapiens.GRCh38.93.gtf
</code></pre>

CC BY-SA 4.0
2018-08-26T13:19:10.677Z
2018-08-26T15:03:52.113Z
2018-08-26T15:03:52.113Z
terdon
<p>You could also do this in R with the GenomicFeatures library.</p>

<pre><code>library(GenomicFeatures)

## make TxDb from GTF file 
txdb &lt;- makeTxDbFromGFF('Homo_sapiens.GRCh38.93.gtf')

## get gene information
all.genes &lt;- genes(txdb)

## import your list of gene names
my.genes &lt;- c('ENSG00000141510','ENSG00000184571','ENSG00000011007')

## get the length of each of those genes
my.genes.lengths &lt;- width(all.genes[my.genes])
## put the names back on the lengths
names(my.genes.lengths) &lt;- my.genes

## print lengths
print(my.genes.lengths)

ENSG00000141510 ENSG00000184571 ENSG00000011007
      25772           55687           18905
</code></pre>

CC BY-SA 4.0
2018-08-27T14:38:18.427Z
2018-08-27T14:38:18.427Z
story
<p>If you are an R user, then you can easily do so with <code>biomaRt</code> </p>

<pre class="lang-r prettyprint-override"><code>library("biomaRt")
library("dplyr")

genes &lt;- read.delim("genes.file.txt", header=T)

head(genes)
          gene_id
1 ENSG00000000003
2 ENSG00000000005
3 ENSG00000000419
4 ENSG00000000457
5 ENSG00000000460
6 ENSG00000000938

## Build a biomart query 
# In the example below, I use the human gene annotation from Ensembl release 82 located on "sep2015.archive.ensembl.org", More about the ensembl_build can be found on "http://www.ensembl.org/info/website/archives/index.html"

dataset="hsapiens_gene_ensembl"
mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL", dataset = dataset, 
host = paste0("sep2015", ".archive.ensembl.org"), path = "/biomart/martservice", archive = FALSE)

annotations &lt;- biomaRt::getBM(mart = mart, attributes=c("ensembl_gene_id", "external_gene_name", "start_position", "end_position"))
annotations &lt;- dplyr::transmute(annotations, ensembl_gene_id, external_gene_name, gene_length = end_position - start_position)

# Filter and re-order gene.annotations to match the order in your input genes list
final.genes &lt;- annotations %&gt;% dplyr::filter(ensembl_gene_id %in% genes<span class="math-container">$gene_id)
final.genes &lt;- final.genes[order(match(final.genes$</span>ensembl_gene_id, genes$gene_id)),]; rownames(final.genes) &lt;-NULL

head(final.genes)
  ensembl_gene_id external_gene_name gene_length
1 ENSG00000000003             TSPAN6       12882
2 ENSG00000000005               TNMD       15083
3 ENSG00000000419               DPM1       23688
4 ENSG00000000457              SCYL3       44636
5 ENSG00000000460           C1orf112      192073
6 ENSG00000000938                FGR       23213

</code></pre>

CC BY-SA 4.0
2020-03-04T13:12:37.890Z
2020-03-04T13:12:37.890Z
Ahmed Alhendi
<p>You can do this directly on <a href="http://useast.ensembl.org/biomart/martview/46d2562c95ab50383e6c3e0e24512ef6" rel="nofollow noreferrer">BioMart site from EBI</a> as well. Using a list of ENSG ids as input, you can get the actual length of each individual transcript, as well as the length of the genomic region coding said transcripts. These are the attributes I used:</p>

<pre><code>Gene stable ID
Transcript stable ID
Transcript length (including UTRs and CDS)
Gene start (bp)
Gene end (bp)
</code></pre>

<p>The output is a table with the relevant data:</p>

<pre><code>Gene ID Transcript ID   Transcript length (including UTRs and CDS)  Gene start (bp) Gene end (bp)
ENSG00000146648 ENST00000455089 3844    55019021    55211628
ENSG00000146648 ENST00000342916 2239    55019021    55211628
</code></pre>

<p>You can change the build as well if you don't want to use GRCh38.</p>

CC BY-SA 4.0
2018-08-27T18:43:56.030Z
2018-08-27T18:43:56.030Z
E. Garcia
<p>I want to find the length of a list of genes, of Homo sapiens, that is reported in the GEO database. I have gathered the ensembl id's of those genes.</p>

<p>I understand this information can be parsed from the start and end position given in GTF file available in ensembl.org. </p>

<p>I would like to ask for advice on how to programmatically download the gtf files with ensembl id's.</p>

<p>On the ensembl webpage a couple of options are listed, API and ftp access. I would like to know if sample scripts are available.</p>

<p>Update: I found a script <a href="https://github.com/dpryan79/Answers/blob/master/SEQanswers_42420/GTF2LengthGC.R" rel="noreferrer">here</a>, it shows how to parse the data from gtf file. Could someone help in understanding how the code can be modified to obtain gene length from start and end position?</p>

<p>Edit 1: 
By start and end position, I refer to the start and end values given in the "fields" section <a href="https://asia.ensembl.org/info/website/upload/gff.html" rel="noreferrer">here</a> and the file from which I want to parse the values is the second last file available in this <a href="ftp://ftp.ensembl.org/pub/current_gtf/homo_sapiens/" rel="noreferrer">link</a>.<br>
For instance, the end - start value of the gene with ensembl id ENSG00000131482,
gene :G6PC</p>

<p>Edit 2: I get the gene names and the expression values from the SOFT files documented in GEO, <a href="https://www.ncbi.nlm.nih.gov/sites/GDSbrowser?acc=GDS4027" rel="noreferrer">link</a></p>

<p>The following is a sample output from SOFT file. It gives me the probe_set(ID_REF) , Gene name and expression values from samples (GSMXXXXXX). Here we see fro G6PC, values are reported from two probe_sets. Can we get the transcript id's from the probe_sets?</p>

<p>Obtaining the transcript id will help me in finding the length of the specific transcript. </p>

<pre><code>&gt; Table(gds)[2449,0:5]
           ID_REF IDENTIFIER GSM388749 GSM388750 GSM388753
2449 1555612_s_at       G6PC   4.39472   4.52235   4.26869
&gt; Table(gds)[16399,0:5]
         ID_REF IDENTIFIER GSM388749 GSM388750 GSM388753
16399 206952_at       G6PC   2.76693   3.45107    2.9815
</code></pre>

CC BY-SA 4.0
2018-08-26T06:06:56.017Z
What do you mean by gene length? Is that the distance from the start of the first CDS to the end of the last CDS in the gene, the length of the longest transcript, or something else?
gringer
CC BY-SA 4.0
2018-08-26T06:19:57.897Z
The start and the end position given in gtf files(I'm trying to obtain thi length), does it include both the coding domain and the non-coding domain? I'm a beginner in this field, excuse me for the naive questions
Natasha
CC BY-SA 4.0
2018-08-26T11:07:50.730Z
That would then be coding, non-coding and intronic regions. What do you need these values for?
Devon Ryan
CC BY-SA 4.0
2018-08-26T11:55:16.853Z
Can you give us an example? Show us a few lines of the GTF file and the output you expect to see from them.
terdon
CC BY-SA 4.0
2018-08-26T12:00:33.527Z
I'm trying to see whether there is a correlation between gene length and the gene expression values reported from micro array studies performed in different platforms.
Natasha
CC BY-SA 4.0
2018-08-26T12:25:48.010Z
OK, but please [edit] your question and show us an example of your input data so we can test our solutions. You also still haven't clarified if you mean the length of the gene (which might include regulatory regions), the length of each transcript (different transcripts will be differentially expressed) or the length of the CDS of each transcript.
terdon
CC BY-SA 4.0
2018-08-26T12:54:01.767Z
@terdon Please check my edit. I don't have the ensembl id's of the transcript. From the GDS files available from the GEO webpage, I have parsed the gene list. I could find only the gene names from those files and from what I understand those files are not annotated with transcript id's.
Natasha
CC BY-SA 4.0
2018-08-26T12:57:33.560Z
There are 4 different gtf files there, each of which has different types of data. I still haven't understood if you really want the start/end position of the gene or of each transcript. If you're looking at expression, you probably need the transcript but you keep referring to genes. You might want to come into our [chat room](https://chat.stackexchange.com/rooms/58858/bioinformatics) so we can discuss this and clarify your question. If you do, please ping me (write `@terdon`).
terdon
CC BY-SA 4.0
2018-08-27T08:34:32.687Z
I can save you time and say that microarray signal is unlikely to be affected by gene length.
Devon Ryan
CC BY-SA 4.0
2018-09-11T14:46:40.900Z
@DevonRyan Realized that after doing the whole task. Thanks anyway:)
Natasha
<gene><ensembl>
Finding gene length using ensembl ID
# Finding gene length using ensembl ID

(Asked by: username_0 on 2018-08-26)

I want to find the length of a list of genes, of Homo sapiens, that is reported in the GEO database. I have gathered the ensembl id's of those genes.
I understand this information can be parsed from the start and end position given in GTF file available in ensembl.org. 
I would like to ask for advice on how to programmatically download the gtf files with ensembl id's.
On the ensembl webpage a couple of options are listed, API and ftp access. I would like to know if sample scripts are available.
Update: I found a script here, it shows how to parse the data from gtf file. Could someone help in understanding how the code can be modified to obtain gene length from start and end position?
Edit 1: 
By start and end position, I refer to the start and end values given in the "fields" section here and the file from which I want to parse the values is the second last file available in this link.
For instance, the end - start value of the gene with ensembl id ENSG00000131482,
gene :G6PC
Edit 2: I get the gene names and the expression values from the SOFT files documented in GEO, link
The following is a sample output from SOFT file. It gives me the probe_set(ID_REF) , Gene name and expression values from samples (GSMXXXXXX). Here we see fro G6PC, values are reported from two probe_sets. Can we get the transcript id's from the probe_sets?
Obtaining the transcript id will help me in finding the length of the specific transcript. 
> Table(gds)[2449,0:5]
           ID_REF IDENTIFIER GSM388749 GSM388750 GSM388753
2449 1555612_s_at       G6PC   4.39472   4.52235   4.26869
> Table(gds)[16399,0:5]
         ID_REF IDENTIFIER GSM388749 GSM388750 GSM388753
16399 206952_at       G6PC   2.76693   3.45107    2.9815

**Tags:** gene, ensembl
> **Comments:**
> **username_1**: What do you mean by gene length? Is that the distance from the start of the first CDS to the end of the last CDS in the gene, the length of the longest transcript, or something else?  
> **username_0**: The start and the end position given in gtf files(I'm trying to obtain thi length), does it include both the coding domain and the non-coding domain? I'm a beginner in this field, excuse me for the naive questions  
> **username_2**: That would then be coding, non-coding and intronic regions. What do you need these values for?  
> **username_3**: Can you give us an example? Show us a few lines of the GTF file and the output you expect to see from them.  
> **username_0**: I'm trying to see whether there is a correlation between gene length and the gene expression values reported from micro array studies performed in different platforms.  
> **username_3**: OK, but please [edit] your question and show us an example of your input data so we can test our solutions. You also still haven't clarified if you mean the length of the gene (which might include regulatory regions), the length of each transcript (different transcripts will be differentially expressed) or the length of the CDS of each transcript.  
> **username_0**: @terdon Please check my edit. I don't have the ensembl id's of the transcript. From the GDS files available from the GEO webpage, I have parsed the gene list. I could find only the gene names from those files and from what I understand those files are not annotated with transcript id's.  
> **username_3**: There are 4 different gtf files there, each of which has different types of data. I still haven't understood if you really want the start/end position of the gene or of each transcript. If you're looking at expression, you probably need the transcript but you keep referring to genes. You might want to come into our [chat room](https://chat.stackexchange.com/rooms/58858/bioinformatics) so we can discuss this and clarify your question. If you do, please ping me (write `@terdon`).  
> **username_2**: I can save you time and say that microarray signal is unlikely to be affected by gene length.  
> **username_0**: @DevonRyan Realized that after doing the whole task. Thanks anyway:)  

---

## 4 answers

### Answer by username_3 on 2018-08-26. Score: 3 | Accepted answer

If you really just want the start and end positions of all genes in a list of genes from Homo_sapiens.GRCh38.93.gtf.gz, you could do this in awk. For example, if your list of genes is:
$ cat genes
ENSG00000131482
ENSG00000223972
ENSG00000228794
ENSG00000187961

You can do:
$ awk '{ 
        if(NR==FNR){
            wantedGenes[$1]++ 
        } 
        else{
            if($3=="gene"){
                gsub(/";*/,"",$10); 
                if($10 in wantedGenes){
                    print $10,$4,$5
                } 
            }
        }
      }' genes Homo_sapiens.GRCh38.93.gtf 
ENSG00000223972 11869 14409
ENSG00000228794 825138 859446
ENSG00000187961 960587 965715
ENSG00000131482 42900797 42913369

Explanation:

if(NR==FNR){ wantedGenes[$1]++ } : NR is the input line number and FNR is the current line number of this input file. The two are only equal while reading the first file. So, if this is the first file, save the first field of each line (the gene name) in the array wantedGenes.
if($3=="gene"){ : if this line is a 'gene' entry.
gsub(/";*/,"",$10); : the gene names in the GTF file are quoted and have an ; after the quote. For example: "ENSG00000187961";. Since we don't have this in the list, we need to remove it so we can match the gene name. This gsub command will remove all " followed by 0 or more ; (the ;* means 0 or more occurrences of ;) from the 10th field of each line. So, it will replace "ENSG00000187961"; with ENSG00000187961.
if($10 in wantedGenes){print $10,$4,$5} : if the 10th field (the modified gene name from above) is in the wantedGenes array, then print the 10th field (the gene name), the 4th (start) and the 5th field (end).

You can easily modify this to print the length instead of the start and end positions:
$ awk '{ 
        if(NR==FNR){
            wantedGenes[$1]++ 
        } 
        else{
            if($3=="gene"){
                gsub(/";*/,"",$10); 
                if($10 in wantedGenes){
                    print $10,$5-$4
                } 
            }
        }
      }' genes Homo_sapiens.GRCh38.93.gtf 
ENSG00000223972 2540
ENSG00000228794 34308
ENSG00000187961 5128
ENSG00000131482 12572

As requested in chat, here's a python version of the same thing:
#!/usr/bin/env python3
import re
import sys

wantedGenes = []
with open(sys.argv[1], mode='r') as f:
    wantedGenes = f.readlines()

wantedGenes = [ x.rstrip() for x in wantedGenes]

print('# Gene\tstart\tend\tlength')
with open(sys.argv[2], mode='r') as f:
    for line in f:
        if not line.startswith('#'): 
            fields = line.split('\t')
            annotations = fields[8].split(' ')
            geneName = re.sub('[";]', '', annotations[1])
            if geneName in wantedGenes and fields[2] == 'gene':
                print('%s\t%s\t%s\t%d' %
                      (geneName, fields[3],fields[4],
                       int( int(fields[4]) - int(fields[3]) )
                      ))

Save the file as foo.py and run with the file names as arguments:
python foo.py geneList.txt Homo_sapiens.GRCh38.93.gtf


---

### Answer by username_4 on 2018-08-27. Score: 3

You could also do this in R with the GenomicFeatures library.
library(GenomicFeatures)

## make TxDb from GTF file 
txdb <- makeTxDbFromGFF('Homo_sapiens.GRCh38.93.gtf')

## get gene information
all.genes <- genes(txdb)

## import your list of gene names
my.genes <- c('ENSG00000141510','ENSG00000184571','ENSG00000011007')

## get the length of each of those genes
my.genes.lengths <- width(all.genes[my.genes])
## put the names back on the lengths
names(my.genes.lengths) <- my.genes

## print lengths
print(my.genes.lengths)

ENSG00000141510 ENSG00000184571 ENSG00000011007
      25772           55687           18905


---

### Answer by username_5 on 2020-03-04. Score: 0

If you are an R user, then you can easily do so with biomaRt 
library("biomaRt")
library("dplyr")

genes <- read.delim("genes.file.txt", header=T)

head(genes)
          gene_id
1 ENSG00000000003
2 ENSG00000000005
3 ENSG00000000419
4 ENSG00000000457
5 ENSG00000000460
6 ENSG00000000938

## Build a biomart query 
# In the example below, I use the human gene annotation from Ensembl release 82 located on "sep2015.archive.ensembl.org", More about the ensembl_build can be found on "http://www.ensembl.org/info/website/archives/index.html"

dataset="hsapiens_gene_ensembl"
mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL", dataset = dataset, 
host = paste0("sep2015", ".archive.ensembl.org"), path = "/biomart/martservice", archive = FALSE)

annotations <- biomaRt::getBM(mart = mart, attributes=c("ensembl_gene_id", "external_gene_name", "start_position", "end_position"))
annotations <- dplyr::transmute(annotations, ensembl_gene_id, external_gene_name, gene_length = end_position - start_position)

# Filter and re-order gene.annotations to match the order in your input genes list
final.genes <- annotations %>% dplyr::filter(ensembl_gene_id %in% genes$gene_id)
final.genes <- final.genes[order(match(final.genes$ensembl_gene_id, genes$gene_id)),]; rownames(final.genes) <-NULL

head(final.genes)
  ensembl_gene_id external_gene_name gene_length
1 ENSG00000000003             TSPAN6       12882
2 ENSG00000000005               TNMD       15083
3 ENSG00000000419               DPM1       23688
4 ENSG00000000457              SCYL3       44636
5 ENSG00000000460           C1orf112      192073
6 ENSG00000000938                FGR       23213


---

### Answer by username_6 on 2018-08-27. Score: 0

You can do this directly on BioMart site from EBI as well. Using a list of ENSG ids as input, you can get the actual length of each individual transcript, as well as the length of the genomic region coding said transcripts. These are the attributes I used:
Gene stable ID
Transcript stable ID
Transcript length (including UTRs and CDS)
Gene start (bp)
Gene end (bp)

The output is a table with the relevant data:
Gene ID Transcript ID   Transcript length (including UTRs and CDS)  Gene start (bp) Gene end (bp)
ENSG00000146648 ENST00000455089 3844    55019021    55211628
ENSG00000146648 ENST00000342916 2239    55019021    55211628

You can change the build as well if you don't want to use GRCh38.


---

