+ All Categories
Home > Technology > Introduction to linux for bioinformatics

Introduction to linux for bioinformatics

Date post: 09-May-2015
Category:
Upload: alberto-labarga
View: 1,558 times
Download: 3 times
Share this document with a friend
Description:
Introduction to linux for bioinformatics
102
Introducción a Linux Transcriptómica y Modelización de Proteínas empleando supercomputación León, 2 de Noviembre de 2011 [email protected]
Transcript
Page 1: Introduction to linux for bioinformatics

Introducción a Linux Transcriptómica y Modelización de Proteínas

empleando supercomputación León, 2 de Noviembre de 2011

[email protected]

Page 2: Introduction to linux for bioinformatics

http://www.linkedin.com/in/albertolabarga

Page 3: Introduction to linux for bioinformatics

http://www.slideshare.net/alabarga

Page 4: Introduction to linux for bioinformatics

http://www.scientifik.info/ngs

Page 5: Introduction to linux for bioinformatics

GNU + Linux

Page 6: Introduction to linux for bioinformatics
Page 7: Introduction to linux for bioinformatics
Page 8: Introduction to linux for bioinformatics

Inicio de sesión en una máquina

a través de la red • Al utilizar la opción ssh ("secure shell"), los usuarios

pueden iniciar una sesión fácilmente en máquinas

remotas ya sea en el mismo lugar o al otro lado del

mundo.

Page 9: Introduction to linux for bioinformatics

http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

putty download

Page 10: Introduction to linux for bioinformatics
Page 11: Introduction to linux for bioinformatics

http://winscp.net/eng/docs/lang:es

winscp download

Page 12: Introduction to linux for bioinformatics
Page 13: Introduction to linux for bioinformatics

Acceso a calendula

Page 14: Introduction to linux for bioinformatics

Acceso a calendula

Page 15: Introduction to linux for bioinformatics

Acceso a calendula

Page 16: Introduction to linux for bioinformatics

Acceso a calendula

$ ssh -X <nombre_usuario>@calendula.fcsc.es -p 2222

Page 17: Introduction to linux for bioinformatics

Shells

• Los usuarios de Linux con frecuencia utilizan un tipo

especial de programa llamado shell para interactuar con

el kernel.

• Sistemas UNIX disponen de diferentes Shell: Bourne

shell (sh), C shell (csh), Korn shell (ksh), TC shell (tcsh),

Bourne Again shell (bash).

• La más popular es la “bash” shell. – echo $SHELL

Page 18: Introduction to linux for bioinformatics

Shells

• La shell se ejecuta dentro de una terminal emitiendo un

"prompt“ y esperando a que le digan qué hacer.

• Luego, el usuario le pide a la shell que ejecute un

programa escribiendo el nombre del programa.

• La shell bash se puede utilizar de modo interactivo o

como un lenguaje de escritura de gran alcance.

• La shell bash guarda el historial de las líneas de

comando ejecutadas. La líneas de comando se pueden

recuperar desde el historial.

Page 19: Introduction to linux for bioinformatics

Para empezar Algunos comandos para ir jugando: whoami – muestra el nombre del usuario id – muestra la información sobre el usuario who – muestra otros usuarios logueados date – fecha/hora del servidor cal – muestra el calendario history – muestra el historial de comandos

Page 20: Introduction to linux for bioinformatics

Manejo de ficheros

Page 21: Introduction to linux for bioinformatics

Listado del contenido de un

directorio con ls • Desde una shell los usuarios pueden utilizar el comando

pwd para conocer donde se encuentran y ls para hacer

un listado del contenido del directorio..ls -al

alabarga@genome2:~$ pwd

/home/alabarga

alabarga@genome2:~$ ls

101x GenomeStudio-Docs.zip

4store GenomeStudio-Software-2009.2.exe

alignment.html gpu

analisisMicroarrays.tar igv papersTesis

apache-solr-1.4.0.zip igv.log pmids.txt

apache-tomcat-6.0.20 IGVTools pubby-0.3

Page 22: Introduction to linux for bioinformatics

Nombres de directorios

especiales

Simbolo Significado

. El actual directorio de trabajo

.. El directorio padre

~ El directorio home del usuario

- El anterior directorio de trabajo

/ El directorio raíz

Page 23: Introduction to linux for bioinformatics

Caracteres Comodines

Caracter Efecto

* coincide con cero o más caracteres (a excepción del punto inicial)

? coincide exactamente con un caracter (a excepción del punto inicial)

[...] coincide exactamente con un caracter de la lista o rango

[^...] coincide exactamente con un caracter no incluido en la lista o rango

Page 24: Introduction to linux for bioinformatics

Ejemplo de Comodines

Patrón Genera la Lista

* todos los archivos en la lista

*.html page1.html page2.html

page*.htm* page1.html page2.html page3.htm page40.htm

image?.* image1.jpeg image2.jpeg

[ps]* page1.html page2.html page3.htm page40.htm script1.pl

[^ps]* image1.jpeg image2.jpeg image10.jpeg image11.jpeg

Page 25: Introduction to linux for bioinformatics

Listado de árboles de

directorios • El comando ls, cuando se da un directorio como

argumento, éste lista el contenido del directorio.

• Por defecto, el comando ls sólo mostrará el contenido

del directorio del nivel más alto.

• Para que el comando ls liste los subdirectorios, puede

añadir la opción -R.

Page 26: Introduction to linux for bioinformatics

Cambio de sitio- El comando cd

• Los Procesos pueden cambiar sus cwd cuando sea

necesario.

• Esto incluye la shell de comando bash, la cual

proporciona el comando cd (del ingleś change directory)

para cambiar el directorio actual desde el intérprete de

comandos.

Page 27: Introduction to linux for bioinformatics

Creación de directorios

(nuevos, vacíos): mkdir • El comando para hacer un directorio nuevo es el

comando mkdir (del inglés make directory).

• Uso: – mkdir [OPCIONES] {DIRECTORIO...}

– Crea el(los) DIRECTORIO(s) si no existe(n). Falla y emite un mensaje

de error si uno o más de los DIRECTORIO(s) existen, pero los nuevos

directorios restantes son aún creados.

Page 28: Introduction to linux for bioinformatics

Borrar directorios (vacíos): rmdir

• El comando para borrar un directorio es rmdir. (remover

directorio).

• Uso: – rmdir [OPCIONES] {DIRECTORIO...}

– Suprime el (los) DIRECTORIO(s) si están vacíos. Emite un mensaje de

error si uno o más del (los) DIRECTORIO(s) no está(n) vacío(s), pero

los directorios que quedan (vacíos) se borran. Tenga en cuenta que un

directorio que contiene sólo un subdirectorio no se considera como

vacío.

Page 29: Introduction to linux for bioinformatics

Ver el contenido de un archivo

con cat • Aunque hay varios comandos disponibles para ver los

archivos, el comando más sencillo es cat.

• Cuando se le da una lista de archivos al comando cat

este concatena los archivos a la salida del terminal.

• También podemos usar more y less

Page 30: Introduction to linux for bioinformatics

El comando head

• head [OPCIONES] [ARCHIVO...]

• Algunas veces todo lo que se necesita al examinar un

archivo es ver las primeras líneas del archivo. El

comando head nos permite hacer esto.

Page 31: Introduction to linux for bioinformatics

El comando tail

• tail [OPCIONES] [ARCHIVO...]

• Para complementar head, el comando tail muestra las

últimas 10 líneas de cada FILE a la salida estándar.

• El comando tail tiene otra opción bastante útil: la opción

-f (follow). Con esta opción tail mostrará las últimas

líneas del archivo y luego "espera" y continua

presentando cualquier nueva línea al ser añadida al

archivo.

Page 32: Introduction to linux for bioinformatics

Copiar archivos

• Puede copiar archivos de un directorio a otro o de un

nombre a otro (renombrarlos) con el comando cp (copy).

• Uso: – cp [OPCIONES] {FUENTE} {DESTINO}

– cp [OPCIONES] {FUENTE...} {DIRECTORIO}

• Ejemplos: – cp saludo.txt hola.txt

– cp hola.txt /tmp

Page 33: Introduction to linux for bioinformatics

Permisos de usuario

Page 34: Introduction to linux for bioinformatics

Cambio de permisos de

archivos: chmod • El comando chmod se utiliza para modificar los permisos

de archivo

• El primer argumento para chmod usa una sintaxis

[ugoa]+/-[rwx] para describir cómo deberían cambiarse

los permisos.

chmod a+w filename

• También puede ser una representación numérica

chmod 775 filename

Page 35: Introduction to linux for bioinformatics

Permisos

• 000 = 0

• 001 = 1

• 010 = 2

• 011 = 3

• 100 = 4

• 101 = 5

• 110 = 6

• 111 = 7

Page 36: Introduction to linux for bioinformatics

Mover/renombrar archivos

• Puede mover archivos de un directorio a otro o de un

nombre a otro (renombrarlos) con el comando mv

(mover).

• Uso: – mv [OPCION...] {FUENTE} {DESTINO}

– mv [OPCION...] {FUENTE...} {DIRECTORIO}

• Ejemplos: – mv saludo.txt borrar.txt

– mv borrar.txt /tmp

Page 37: Introduction to linux for bioinformatics

Borrar archivos

• Se pueden suprimir (eliminar, borrar) archivos con el

comando rm (remove).

• Uso: – rm [OPCIONES] {ARCHIVO...}

• Examples: – rm /tmp/borrar.txt

Page 38: Introduction to linux for bioinformatics

Copiar árboles de directorios

• El comando cp puede ser usado para copiar arboles de

directorios completos con la opción: -r (recursivo).

cp –R seq2011 backup

Page 39: Introduction to linux for bioinformatics

Borrar árboles de directorios

• Con la opción correcta, el comando rm puede borrar o

eliminar arboles de directorios completos.

rm –R backup

Page 40: Introduction to linux for bioinformatics

Entrada estándar (stdin), salida estándar

(stdout), error standard (stderror)

• Los programas de terminal suelen leer información como

un flujo desde una sola fuente tal como el teclado de

una terminal (stdin)

• Generalmente, escriben información como un flujo a un

solo destino como por ejemplo una pantalla (stdout)

• Generalmente, stdin y stdout están conectadas a la

terminal que ejecuta el comando.

• Se considera conveniente redirigir (stdin) desde (stdout)

hacia los archivos.

• Los programas Unix reportan condiciones de error a un

destino llamado error estándar (stderr).

Page 41: Introduction to linux for bioinformatics

Descriptores de Archivos

Flujo Descriptor Abreviación

Standard In 0 stdin

Standard Out 1 stdout

Standard Error 2 stderr

• Como protocolo de Linux (y Unix), cada proceso hereda tres archivos abiertos tras el inicio. – Primero, descriptor de archivo 0, es la entrada estándar.

– Segundo, descriptor de archivo 1, es la salida estándar.

– Tercero, descriptor de archivo 2, es el error estándar.

Page 42: Introduction to linux for bioinformatics

Redirección de stdin, stdout y

stderr en bash

sintaxis efecto

cmd < file Redirigir stdin desde file

cmd > file Redirigir stdout a file. Reescribir si existe

cmd >> file Redirigir stdout a file. Agregar si existe

cmd 2> file Redirigir stderr a file. Reescribir si existe

cmd 2>> file Redirigir stderr a file. Agregar si existe

cmd > file 2>&1 Combinar stdout y stderr a file

cmd >& file Combinar stdout y stderr a file

Page 43: Introduction to linux for bioinformatics

Ejemplo

alabarga@genome2:~$ ls *.zz

ls: cannot access *.zz: No such file or directory

alabarga@genome2:~$ ls *.zz > zz.txt

ls: cannot access *.zz: No such file or directory

alabarga@genome2:~$ cat zz.txt

alabarga@genome2:~$ ls *.zz >& zz.txt

alabarga@genome2:~$ cat zz.txt

ls: cannot access *.zz: No such file or directory

Page 44: Introduction to linux for bioinformatics

Búsquedas

• find – find -name "*pattern*" # searches for *pattern* in and below current

directory

– find /usr/local -name "*blast*" # finds file names *blast* in directory

– find /usr/local -iname "*blast*" # same as above, but case insensitive

– find . -mtime -1

– find . -mtime -1 –ls

– find / -size +10000k

• additional useful arguments: -user <user name>, -group

<group name>, -ctime <number of days ago changed>

Page 45: Introduction to linux for bioinformatics

Búsquedas

• locate – locate "*.dat" –q

– -i, in case you wanted to perform a case insensitive search

– -c, instead of writing file names on standard output, write the number of

matching entries only.

• which <application_name> # location of application

• whereis <application_name> # searches for executables

Page 46: Introduction to linux for bioinformatics

wget

• Descarga recursos de modo recursivo, en ambiente no

interactivo de los protocolos HTTP, HTTPS y FTP.

• Cuando se llama con una URL como su argumento, el

comando wget recupera el contenido de la URL y lo

almacena en un archivo local en el directorio actual de

trabajo del mismo nombre.

• wget -O -

http://www.ebi.ac.uk/Tools/dbfetch/dbfetch

/uniprot/P01174/fasta

Page 47: Introduction to linux for bioinformatics

Tamaño

• df # disk space

• free -g # memory info in Megabytes

• du -sh # disk space usage of current directory

• du -sh * # disk space usage of files/directories

• du -s * | sort -nr # shows disk space used by different

directories/files sorted by size

Page 48: Introduction to linux for bioinformatics

Procesos

Page 49: Introduction to linux for bioinformatics

The ps command

• El comando ps se utiliza comúnmente para enumerar los

procesos ejecutándose en un sistema.

• El comando ps, sin ningún argumento, muestra todos los

procesos que se iniciaron desde una sola terminal.

alabarga@genome2:~$ ps

PID TTY TIME CMD

22047 pts/0 00:00:00 bash

22472 pts/0 00:00:00 ps

Page 50: Introduction to linux for bioinformatics

The ps command

• ps # Shows processes running by user

ps -e # Shows all processes on system

ps ax –tree # Shows the child-parent hierarchy of all processes

ps -o %t -p <pid> # Shows how long a particular process was

running.

• ps <pid> | cat

• ps aux | grep <user_name> # Shows all processes of one user

Page 51: Introduction to linux for bioinformatics

top

Page 52: Introduction to linux for bioinformatics

Edición de ficheros

de texto

Page 53: Introduction to linux for bioinformatics

Vim: control

• vi my_file

• i # INSERT MODE

• R # replace MODE

• ESC # NORMAL (NON-EDITING) MODE

Page 54: Introduction to linux for bioinformatics

vim

• : # commands start with ':'

• :w # save command; if you are in editing mode you have

to hit ESC first!!

• :w new_filename # saves into new file

• :#,#w new_filename # saves specific lines (#,#) to new

file

• :q # quit file, don't save

• :q! # exits WITHOUT saving any changes you have

made

• :wq # save and quit

Page 55: Introduction to linux for bioinformatics

Vim: moving around

• :# go to specified line number

• $ # moves cursor to end of line

• A # same as $, but switches to insert mode

• 0 (zero) # moves cursor to beginning of line

• CTRL-g # shows at status line filename and the line you

are on

• SHIFT-G # brings you to bottom of file, type line number

(isn't displayed) then SHIFT-G # brings you to specified

line#

Page 56: Introduction to linux for bioinformatics

Vim: more commands

• d$ # deletes from cursor to the end of the line

• dd # deletes entire line

• :s/old_pat/new_pat/ # replaces first occurrence in a line

• :s/old_pat/new_pat/g # replaces all occurrence in a line

• :%s/old_pat/new_pat/g # replaces all occurrence in file

• u # undo last command

Page 57: Introduction to linux for bioinformatics

Utilitarios de Compresión

Standard de Linux • zip/unzip (.zip)

• gzip (.gz) – el más versatil y más común utilitario de descompresión usado

• bzip2 (.bz) – produce la mas compacta compresión de archivos

– más uso intesivo de CPU

• compress/uncompress (.Z) – No es usualmente instalado por defecto

Page 58: Introduction to linux for bioinformatics

Archivadores de Archivos

• El archivo contiene el directorio y sus archivos y

subdirectorios subyacentes, empaquetados como un

solo archivo.

• En Linux (y Unix), el comando más común para crear y

extraer archivos es el comando tar.

• El archivo contiene el directorio y sus archivos y

subdirectorios subyacentes, empaquetados como un

solo archivo.

• A estos paquetes de archivos suele dárseles la

extensión del nombre de archivo .tar.

Page 59: Introduction to linux for bioinformatics

Comandos Básicos Tar

Opción Efecto

-c, --create Crea un empaquetador de archivos

-x, --extract Extraer un empaquetador de archivos

-t, --list List el contenido de un empaquetador de archivos

Page 60: Introduction to linux for bioinformatics

Opciones del comando tar

Opción Efecto

-C, --directory=DIR Cambia al directorio DIR

-P, --absolute-reference sin / inicial desde los nombres de archivos

-v, --verbose Lista los archivos procesados

-Z, --compress internally compress archive

-z, --gzip internamente gzip el archivo

-j, --bzip2 internamente bzip2 el archivo

Page 61: Introduction to linux for bioinformatics

Manipulación de ficheros

de texto

Page 62: Introduction to linux for bioinformatics

Comando Word Count (wc)

• El comando wc cuenta el numero de caracteres,

palabras y lineas.

• Tomará su entrada ya sea de archivos llamados en su

línea de comandos o desde su entrada estándar.

wc [-c] [-l] [-w] [filename…]

Page 63: Introduction to linux for bioinformatics

Tuberías

• El flujo de stdout desde un proceso puede estar

conectado al flujo de stdin de otro proceso mediante lo

que Unix llama una "tubería".

• Varios de los comandos en Unix están diseñados para

operar como un filtro, leer la entrada desde stdin y

enviar la salida a stdout.

• bash usa "|" para crear una tubería entre dos

comandos.

Page 64: Introduction to linux for bioinformatics

Ordenando todo: sort

• Conceptos clave – El comando sort clasifica datos en orden alfabético.

– sort -n ordena numéricamente.

– sort -u clasifica y suprime duplicados.

– sort -k y -t clasifica en un campo específico.

– sort –r ordena a la inversa

ls -s | sort -n

Page 65: Introduction to linux for bioinformatics

sort

• # sort by 2nd field (lexicographic sort)

• sort -k 2 arrayDat.txt

• # sort by 2nd field (numeric sort)

• sort -n -k 2 arrayDat.txt

Page 66: Introduction to linux for bioinformatics

El comando uniq

• El programa uniq se utiliza para identificar, contar o

suprimir registros duplicados en la información

clasificada.

-c , número de ocurrencias

-u sólo líneas únicas

-d, solo aquellos duplicados

-f n , evita los n primeros campos

-s n, evita n caracteres

-i, gnora mayúsculas o minúsculas

Page 67: Introduction to linux for bioinformatics

El comando uniq

# count how many unique rows

uniq arrayAnnot.txt | wc –l

# count unique rows without considering the probe ID

uniq -f 1 arrayAnnot.txt | wc –l

# report genes and count number of occurrences

uniq -f 1 -c arrayAnnot.txt

# report list of unique genes

uniq -f 1 -u arrayAnnot.txt

Page 68: Introduction to linux for bioinformatics

cut

• cut imprime determinados campos de una tabla # -d specifies column separator (tab is default),

# -f specifies column numbers.

• cut -d: -f1,5 /etc/passwd

• cut -f 1 arrayDat.txt

Page 69: Introduction to linux for bioinformatics

paste

• Este comando “pega” las columnas de dos ficheros

• # put each column in a separate tmp files cut -f 1

arrayAnnot.txt > tmp1

• cut -f 2 arrayAnnot.txt > tmp2

• cut -f 3 arrayAnnot.txt > tmp3

• # merge lines in a new column order

• paste tmp3 tmp1 tmp2 > arrayAnnotOrdered.txt

Page 70: Introduction to linux for bioinformatics

join

• # join two files (use 1st field as key)

• join arrayDat.txt arrayAnnot.txt

• # probeID is the second field in the file

• join -1 2 -2 1 arrayAnnotOrdered.txt arrayDat.txt

• # specify which field to output for each file

• join -1 2 -o '1.1 2.2 2.3 2.4 2.5' arrayAnnotOrdered.txt

arrayDat.txt

Page 71: Introduction to linux for bioinformatics

Búsqueda de Texto: grep

• Acrónimo de “general regular expression print”, grep es

un comando que imprime en pantalla líneas coincidentes

con un patrón de una cadena de texto especificado.

• grep suele utilizarse como filtro para reducir salida a

sólo lo deseado.

• Permite buscar múltiples patrones

Page 72: Introduction to linux for bioinformatics

grep: algunas opciones

• grep -v imprime líneas NO coincidentes con una cadena

o patrón de texto.

• grep –w busca el patrón como palabra completa

• grep –i no distingue mayúsculas y minúsculas

• grep –c cuenta las líneas coincidentes

• grep –n añade el número de línea

• grep –f toma los patrones de un fichero

Page 73: Introduction to linux for bioinformatics

grep

• # print lines that match “chr”

• grep chr arrayAnnot.txt

• # print lines that match “chr” as a whole word

• grep -w chr arrayAnnot.txt

• # print lines that match “chromosome” as a whole word

• grep -w chromosome arrayAnnot.txt

Page 74: Introduction to linux for bioinformatics

grep

• # print how many lines match the pattern "orf"

• grep -c orf arrayAnnot.txt

• # preceed the matching line with the line number

• grep -n orf arrayAnnot.txt

Page 75: Introduction to linux for bioinformatics

grep

• # make a list with 5 gene symbols

• cut -f 3 arrayAnnot.txt | head -n 5 > tmp

• # use list "tmp" to match lines in arrayAnnot.txt

• grep -f tmp arrayAnnot.txt

Page 76: Introduction to linux for bioinformatics

sed: string replacement

• Reemplazar: sed –e „s/regex/replacement/‟

• # substitute “chr” with “chromosome”

• head myfile.sam | sed s/chr/chromosome/g

• Borrar lineas 1-10: sed -e '1,10d„

• Borrar comentarios: sed -e '/^#/d„

• Borrar lineas en blanco: sed -e '/^$/d„

Page 77: Introduction to linux for bioinformatics

tr

También podemos utilizar tr

• echo HELLO | tr 'A-Z' 'a-z'

Page 78: Introduction to linux for bioinformatics

awk

• AWK es un lenguaje de programación diseñado

para procesar datos basados en texto, ya sean

ficheros o flujos de datos

• awk /patrón/ {acción} AWK mira a lo largo del

fichero de entrada; cuando encuentra una línea

que coincide con el "patrón", ejecuta la (s)

órdenes (s) indicadas en "acción".

Page 79: Introduction to linux for bioinformatics

awk

• Las formas alternativas incluyen: BEGIN { acción }

Ejecuta las órdenes acción al comienzo de la ejecución, antes de que los

datos comiencen a ser procesados.

END { acción }

Similar a la forma previa pero ejecuta las órdenes acción después de que

todos los datos sean procesados.

Page 80: Introduction to linux for bioinformatics

awk

• FILENAME es el fichero de entrada

• record variable: $0 se refiere a la línea entera

• field variables: $1 se refiere al primer campo, $2 al

segundo, etc.

• NR es el número de línea

• NF es el número de campos de la línea

• FS es el separador de campos

Page 81: Introduction to linux for bioinformatics

awk

$ awk –F”:” „{print $1 “ “ $3}‟ /etc/passwd

Awk

executable

pattern

to search

Action to

perform on line

If pattern matches

The file

to operate

upon

Field

Separator

Page 82: Introduction to linux for bioinformatics

awk

• # print 1st field only

• awk '{print $1}' arrayDat.txt

• # rearrange the fields, separated by a tab

• awk '{print $1, "\t", $3, "\t", $2}' arrayDat.txt

• # print the number of fields for each record

• awk '{print NF}' arrayDat.txt

• # print the last field of each record

• awk '{print $NF}' arrayDat.txt

Page 83: Introduction to linux for bioinformatics

awk

• # print first 5 records, excluding headers

• awk 'NR > 1 && NR < 7' arrayDat.txt

• # print the total number of records

• awk 'END {print NR}' arrayDat.txt

Page 84: Introduction to linux for bioinformatics

awk

• # print the lines that match the string "orf"

• awk '/orf/' arrayAnnot.txt

• # print the probe IDs whose annotation contains "orf"

• awk '/orf/ {print $1}' arrayAnnot.txt

Page 85: Introduction to linux for bioinformatics

awk

• # print sum of values for each probe

• awk 'NR > 1 {s=0; for (i=2; i<=NF; i++) s=s+$i; print $1,

s}' arrayDat.txt

• # print mean of values for each probe

• awk 'NR > 1 {s=0; n=NF-1; for (i=2; i<=NF; i ++) s=s+$i;

s=s/n; print s}' arrayDat.txt

Page 86: Introduction to linux for bioinformatics

sed/awk

sed '/^>/d' F5R3.fasta | sort | uniq | awk '{print ">SEQ"NR"\n"$0 }'

Page 87: Introduction to linux for bioinformatics

csplit

# splits fasta batch file into many files

# at '>„

csplit -f out F5R3.fasta "%^>%" "/^>/" "{*}"

Page 88: Introduction to linux for bioinformatics

Ejercicio: archivos SAM

• How many alignments are in the file?

• How many distinct sequences are in the file?

• How many reads have multiple hits?

• What chromosomes are represented?

• How many reads map to each chromosome?

• Which are the most and least represented

chromosomes?

• Do the reads have variable length?

Page 89: Introduction to linux for bioinformatics

Ejercicio: archivos SAM

• How many alignments are in the file? • wc -l myfile.sam

• How many distinct sequences are in the file?

• # which column has the sequence

• head myfile.sam |cut -f10

• # sort, uniq and count the sequence

• cut -f 10 myfile.sam | sort | uniq | wc -l

Page 90: Introduction to linux for bioinformatics

Ejercicio: archivos SAM

• How many reads have multiple hits?

• cut -f 1 myfile.sam | sort | uniq -d | wc –l

• What chromosomes are represented?

• cut -f 3 myfile.sam | sort | uniq

• How many reads map to each chromosome?

• cut -f 3 myfile.sam | sort | uniq -c

Page 91: Introduction to linux for bioinformatics

Ejercicio: archivos SAM

• Which are the most and least represented

chromosomes?

• cut -f 3 myfile.sam | sort | uniq -c | sort -n | tail -n 1

• cut -f 3 myfile.sam | sort | uniq -c | sort -n | head -n 1

• Do the reads have variable length?

• awk '{print length($10)}' myfile.sam | sort | uniq -c

• wc -l myfile.sam

Page 92: Introduction to linux for bioinformatics

Ejercicio: archivos SAM

• Put the first 10 identifier and reads into single, distinct

tab files.

• cut -f 1,10 myfile.sam | head | split -l 1

• Remove the tab files created above

• rm xa?

• Verify that all reads have same length.

• awk '{print length($10)}' myfile.sam | sort | uniq

• Find how many reads are mapping to the negative

strand.

• cut -f2 myfile.sam | grep -c 16

• cut -f2 myfile.sam | sort | uniq -c

Page 93: Introduction to linux for bioinformatics

Ejercicio: datos en tablas

• En un experimento con microarrays, para cada gen

queremos la mayor intensidad media

• Los archivos que tenemos son: – arrayDat.txt: probeID and four sample intensity values.

– arrayAnnot.txt: probeID, gene descriptions, gene symbols.

Page 94: Introduction to linux for bioinformatics

Ejercicio: datos en tablas

# compute the average intensity for each probeID

awk 'NR > 1 {s=0; n=NF-1; for (i=2; i<=NF; i++) s=s+$i; s = s/n;

print $1,"\t",s}' arrayDat.txt | sort > tmp1

# select only probeID and geneSymbol fields

awk 'NR > 1 {print $1, "\t", $NF}' arrayAnnot.txt | sort > tmp2

# annotate the average intensity values of each probeID with the

gene symbol

join tmp1 tmp2 > tmp3

# neglect probeID, then sort in reverse order with gene symbol as

key, and finally grab unique rows ignoring the values.

awk '{print $2, "\t", $3}' tmp3 | sort -r -k 2 | uniq -f 1

Page 95: Introduction to linux for bioinformatics

Web Services

Page 96: Introduction to linux for bioinformatics

Webservices

• wget http://www.uniprot.org/uniprot/P03973.fasta

Page 97: Introduction to linux for bioinformatics

EBI Web Services

• http://www.ebi.ac.uk/Tools/webservices/

• java -Djava.ext.dirs=lib -jar NCBIBlast_JAXWS.jar

-p blastp -D uniprotkb_swissprot --stype protein

--email [email protected]

--outformat out --outfile - P03973.fasta

Page 98: Introduction to linux for bioinformatics

Parsing

• grep -E '(SP:|TR:)' blast.output |

cut -f1 -d" " |

cut -d: -f2 |

xargs -I _PROT_

wget -O -

http://www.uniprot.org/uniprot/_PROT_.fasta

>> secuencias_recuperadas.txt

Page 99: Introduction to linux for bioinformatics

Shell scripts

Page 100: Introduction to linux for bioinformatics

A shell script is a text file with a list of commands inside. Shell scripts are good for automating tasks you use often, or running batch jobs. Enter the following in a new file, script.sh:

echo “Date and time is:”

date

echo “Your current directory is:”

pwd

Run the script like this: sh script.sh

Shell Scripts

Page 101: Introduction to linux for bioinformatics

A more advanced shell script utilizing a loop: for num in 1 2 3

do

echo “We are on $num…”

done

More Shell Scripts

Page 102: Introduction to linux for bioinformatics

Paso de parámetros

#!/bin/sh

# split fasta file into separate sequence files

#

if [ $# -gt 1 ] then

seqfile="$1"

destdir="$2“

else

echo "Use: fsplit SEQFILE DESTDIR"

echo "Splits fasta file SEQFILE into separate files in DESTDIR

folder"

exit

fi

mkdir $2

csplit -f $destdir/sequence $seqfile "%^>%" "/^>/" "{*}" -s


Recommended