Post on 15-Apr-2017
Sistemas Operativos I
Comandos de GNU/Linux: 2da parte
Angel Vázquez-Patiñoangel.vazquezp@ucuenca.edu.ec
Departamento de Ciencias de la ComputaciónUniversidad de Cuenca
21 de junio de 2016
Filtrado
Ordenamiento
Comparación
Búsqueda
Respaldo
2/69
Filtrado de archivos
3/69
● egrep● fgrep● grep● uniq
egrep, fgrep, grep y uniq
● Muchas veces es muy útil filtrar contenido de archivos, seleccionando líneas que cumplan con un criterio
● La principal diferencia entre los comandos grep, egrep y fgrep es el tipo de patrones de texto que pueden filtrar
4/69
egrep, fgrep, grep y uniq
5/69
● fgrep, puede buscar únicamente “fixed strings”
● egrep, soporta expresiones regulares● fgrep, soporta una opción adicional –
x, que muestra las líneas que son exactamente iguales al string
● La opción –n hace que se muestre el número de línea donde se encuentra el patrón
● La opción –i hace que no se hagan caso a mayúsculas o minúsculas
● La opción –l muestra el listado de archivos que contienen el patrón específico
● La opción –v muestra las líneas que no contienen el patrón
● La opción –w hace que se tomen en cuenta palabras completas
egrep, fgrep, grep y uniq
6/69
egrep, fgrep, grep y uniq
7/69
-w palabras completas-n número de líneas donde están
egrep, fgrep, grep y uniq
8/69
-v revierte el filtro
egrep, fgrep, grep y uniq
9/69
egrep, fgrep, grep y uniq
10/69
Expresiones regulares
● Secuencias de caracteres que describen cadenas de texto que cumplen con una condición
11/69
Expresiones regulares
12/69
Patrón
Expresiones regulares
13/69
Patrón
Expresiones regulares
14/69
Patrón
Expresiones regulares
15/69
Patrón
Expresiones regulares
16/69
Patrón
Expresiones regulares
17/69
Patrón
Expresiones regulares
18/69
Patrón
Expresiones regulares
19/69
Patrón
Expresiones regulares
20/69
Patrón
Expresiones regulares
21/69
Patrón
Expresiones regulares
22/69
● Comandos como egrep soportan expresiones regulares extendidas
Expresiones regulares
23/69
egrep, fgrep, grep y uniq
● El comando uniq reporta u omite líneas repetidas
● Con la opción -c se muestra al inicio de la línea el número de ocurrencias
24/69
egrep, fgrep, grep y uniq
$ cat animals.txt
cat snake
monkey snake
dolphin elephant
dolphin elephant
goat elephant
pig pig
pig pig
monkey pig
$ uniq animals.txt
cat snake
monkey snake
dolphin elephant
goat elephant
pig pig
monkey pig
25/69
$ uniq -c animals.txt
1 cat snake
1 monkey snake
1
2 dolphin elephant
1 goat elephant
2
2 pig pig
1 monkey pig
$ uniq -1 animals.txt
cat snake
dolphin elephant
pig pig
Ordenamiento de archivos
● Sort
26/69
sort
● Ordena un archivo en orden ascendente o descendente basado en uno o más campos de ordenamiento
● -r especifica ordenamiento descendiente● -t especifica otro carácter separador (por defecto se usa
el espacio)● -f hace que se ignore entre mayúsculas y minúsculas● -M ordena el campo en formato de mes● -n ordena el campo en formato numérico● -b ignora espacios sort
27/69
sort
$ cat sortfile.txt
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan Start chapter 5 23rd
Jan End chapter 7 23rd
Mar Start chapter 6 27
may End chapter 7 17th
Apr End Chapter 5 1
Feb End chapter 1 14
28/69
$ sort sortfile.txt
Apr End Chapter 5 1
Feb End chapter 1 14
Jan End chapter 7 23rd
Jan Start chapter 1 30th
jan Start chapter 3 10th
Jan Start chapter 5 23rd
Mar Start chapter 6 27
may End chapter 7 17th
sort
$ cat sortfile.txt
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan Start chapter 5 23rd
Jan End chapter 7 23rd
Mar Start chapter 6 27
may End chapter 7 17th
Apr End Chapter 5 1
Feb End chapter 1 14
29/69
$ sort -r sortfile.txt
may End chapter 7 17th
Mar Start chapter 6 27
Jan Start chapter 5 23rd
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan End chapter 7 23rd
Feb End chapter 1 14
Apr End Chapter 5 1
sort
● Se puede ordenar por algún campo en particular utilizando + seguido del campo final de parada especificado por un -
30/69
sort
$ cat sortfile.txt
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan Start chapter 5 23rd
Jan End chapter 7 23rd
Mar Start chapter 6 27
may End chapter 7 17th
Apr End Chapter 5 1
Feb End chapter 1 14
31/69
$ sort -r +0 -1 sortfile.txt
may End chapter 7 17th
Mar Start chapter 6 27
Jan Start chapter 5 23rd
Jan Start chapter 1 30th
Jan End chapter 7 23rd
jan Start chapter 3 10th
Feb End chapter 1 14
Apr End Chapter 5 1
sort
$ cat sortfile.txt
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan Start chapter 5 23rd
Jan End chapter 7 23rd
Mar Start chapter 6 27
may End chapter 7 17th
Apr End Chapter 5 1
Feb End chapter 1 14
32/69
$ sort +3 -4 sortfile.txt
Feb End chapter 1 14
Jan Start chapter 1 30th
jan Start chapter 3 10th
Apr End Chapter 5 1
Jan Start chapter 5 23rd
Mar Start chapter 6 27
Jan End chapter 7 23rd
may End chapter 7 17th
sort
● Para ordenar utilizando meses (M) e ignorando los espacios en blanco (b)
33/69
sort
$ cat sortfile.txt
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan Start chapter 5 23rd
Jan End chapter 7 23rd
Mar Start chapter 6 27
may End chapter 7 17th
Apr End Chapter 5 1
Feb End chapter 1 14
34/69
$ sort +0 -1 -bM sortfile.txt
Jan End chapter 7 23rd
Jan Start chapter 1 30th
jan Start chapter 3 10th
Jan Start chapter 5 23rd
Feb End chapter 1 14
Mar Start chapter 6 27
Apr End Chapter 5 1
may End chapter 7 17th
sort
● Se pueden ordenar varios campos a la vez por distintos criterios
35/69
sort
$ cat sortfile.txt
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan Start chapter 5 23rd
Jan End chapter 7 23rd
Mar Start chapter 6 27
may End chapter 7 17th
Apr End Chapter 5 1
Feb End chapter 1 14
36/69
$ sort -r +0 -1 -bM +3 -4 sortfile.txt
may End chapter 7 17th
Apr End Chapter 5 1
Mar Start chapter 6 27
Feb End chapter 1 14
Jan Start chapter 5 23rd
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan End chapter 7 23rd
sort
$ cat sortfile.txt
jan Start chapter 3 10th
Jan Start chapter 1 30th
Jan Start chapter 5 23rd
Jan End chapter 7 23rd
Mar Start chapter 6 27
may End chapter 7 17th
Apr End Chapter 5 1
Feb End chapter 1 14
37/69
$ sort +0 -1 +4 -5 sortfile.txt
Apr End Chapter 5 1
Feb End chapter 1 14
jan Start chapter 3 10th
Jan End chapter 7 23rd
Jan Start chapter 5 23rd
Jan Start chapter 1 30th
Mar Start chapter 6 27
may End chapter 7 17th
Comparación de archivos
38/69
● cmp
● diff
38/69
cmp
● cmp: encuentra el primer byte que difiere entre dos archivos
● diff: muestra todas las diferencias y similitudes entre dos archivos
Utility: cmp -ls fileName1 fileName2 [offset1] [offset2]
● Si dos archivos son idénticos, no muestra salida en pantalla y su código de salida es 0, caso contrario la salida es 1 y se muestra información de dónde está la diferencia
● -l muestra el valor de distancia en bytes donde está la diferencia● -s provoca que la salida no sea mostrada a la consola● Offset1 y offset2 son valores opcionales que hacen que se inhiban los
primeros● offset1 u offset2 bytes de los respectivos archivos donde la comparasión
debe comenzar
39/69
cmp
$ cat lady2.txt
Lady of the night,
I hold you close to me,
And everything you say to me is right.
$ cat lady3.txt
Lady of the night,
I hold you close to me,
And everything you say to me is right.
It makes me feel,
I'm so in love with you.
Even in the dark I see your light.
40/69
$ cat lady1.txt
Lady of the night,
I hold you close to me,
And all those loving words you say are right.
$ cmp lady1.txt lady2.txt
lady1.txt lady2.txt differ: byte 48, line 3
$ cmp lady2.txt lady3.txt
cmp: EOF on lady2.txt
$ cmp lady3.txt lady3.txt
cmp
$ cmp -l lady1 lady2 ...muestra bytes no iguales
48 141 145
49 154 166
...
81 145 56
82 40 12
cmp: EOF on lady2 ...lady2 más pequeño que lady1
$ _
41/69
diff
Utility: diff -i -dflag file1 file2
● Compara dos archivos y muestra una descripción de sus diferencias
● La opción -i (ignore) hace que las letras mayúsculas y minúsculas sean consideradas iguales
42/69
diff
● Additions
firstStart a secondStart, secondStop
> lines from the second file to add to the first file ● Deletions
firstStart, firstStop d lineCount
< lines from the first file to delete ● Changes
firstStart, firstStop c secondStart, secondStop
< lines in the first file to be replaced
--
> lines in the second file to be used for the replacement
43/69
diff
$ cat lady1 ...look at the first test file
Lady of the night,
I hold you close to me,
And all those loving words you say are right.
$ cat lady2 ...look at the second test file
Lady of the night,
I hold you close to me,
And everything you say to me is right.
$ diff lady1 lady2 ...compare lady1 and lady2
3c3
< And all those loving words you say are right.
--
> And everything you say to me is right.
44/69
diff
$ cat lady2 ...look at the second test file.
Lady of the night,
I hold you close to me,
And everything you say to me is right.
$ cat lady3 ...look at the third test file.
Lady of the night,
I hold you close to me,
And everything you say to me is right.
It makes me feel,
I'm so in love with you.
Even in the dark I see your light.
$ diff lady2 lady3 ...compare lady2 and lady3.
3a4,6
> It makes me feel,
> I'm so in love with you.
> Even in the dark I see your light.
45/69
diff
$ cat lady3 ...look at the third test file.
Lady of the night,
I hold you close to me,
And everything you say to me is right.
It makes me feel,
I'm so in love with you.
Even in the dark I see your light.
$ cat lady4 ...look at the fourth test file.
Lady of the night,
I'm so in love with you.
Even in the dark I see your light.
$ diff lady3 lady4 ...compare lady3 and lady4.
2,4d1
< I hold you close to me,
< And everything you say to me is right.
< It makes me feel,
46/69
Búsqueda de archivos
● find
47/69
find
● Recursivamente analiza directorios y aplica expresiones de comparación a cada archivo
48/69
find● Recursivamente analiza directorios y aplica
expresiones de comparación a cada archivoExpresión Valor o acción
-name pattern True if the file's name matches pattern, which may include the shell metacharacters *, [, ], and ?.
-perm oct True if the octal description of the file's permission flags is exactly equal to oct.
-type ch True if the type of the file is ch (b = block, c = char, etc.).
-user userId True if the owner of the file is userId.
-group groupId
True if the group of the file is groupId.
-atime count True if the file has been accessed within count days.
-mtime count True if the contents of the file have been modified within count days.
expr1 -o expr2 Short-circuiting or; if expr1 is true, it returns true. If expr1 is false, it returns the value of expr2.
49/69
find● Recursivamente analiza directorios y aplica
expresiones de comparación a cada archivo
Expresión Valor o acción
-ctime count True if the contents of the file have been modified within count days or if any of its attributes have been altered.
-exec command True if the exit code from executing command is 0. command must be terminated by an escaped semicolon (\;). If you specify {} as a command-line argument, it is replaced by the name of the current file.
-print Prints out the name of the current file and returns true.
-ls Displays the current file's attributes (equivalent of ls -dils) and returns true.
-cpio device Writes the current file in cpio format to device and returns true.
!expression Returns the logical negation of expression.
expr1 [-a] expr2 Short-circuiting and; if expr1 is false, it returns false and expr2 is not executed. If expr1 is true, it returns the value of expr2.
50/69
find
$ find . -name '*.txt' -print
./sortfile (copy).txt
./subdirectorio/archivoTexto.txt
./subdirectorio/archivoPoemas.txt
./subdirectorio/code.txt
./subdirectorio/holaMundo.txt
./subdirectorio/profesores.txt
./animals.txt
./lady2.txt
./sortfile.txt
./animals (copy).txt
./grepfile2.txt
./archivo1.txt
./lady3.txt
./grepfile.txt
./lady1.txt
51/69
find
$ find /home/angelv/Dropbox/Docencia/2016\ mar-ago/Sistemas\ operativos\ I/ -mtime 10
/home/angelv/Dropbox/Docencia/2016 mar-ago/Sistemas operativos I/prácticas/9 redes
/home/angelv/Dropbox/Docencia/2016 mar-ago/Sistemas operativos I/sistemas-operativos.zip
52/69
find
$ find /home/angelv/Dropbox/Docencia/2016\ mar-ago/Sistemas\ operativos\ I/ -mtime 10 -ls
13738196 8 drwxrwxr-x 2 angelv angelv 4096 Jun 8 08:19 /home/angelv/Dropbox/Docencia/2016\ mar-ago/Sistemas\ operativos\ I/pr\303\241cticas/9\ redes
23330944 28288 -rw-rw-r-- 1 angelv angelv 28956821 Jun 8 12:35 /home/angelv/Dropbox/Docencia/2016\ mar-ago/Sistemas\ operativos\ I/sistemas-operativos.zip
53/69
find
$ find . -name '*.bak' -ls -exec rm {} \;
...ls and then remove all files
...that end with ".bak".
285451 4 -rw-r--r-- 1 glass cs 9 May 16 12:01 ./a.bak
282849 4 -rw-r--r-- 1 glass cs 9 May 16 12:01 ./b.bak
284438 16 -rw-r--r-- 1 glass cs 15630 Jan 26 00:14 ./s6/g.bak
284427 20 -rw-r--r-- 1 glass cs 18481 Jan 26 12:59 ./s6/g2.bak
54/69
find
$ find . \( -name '*.c' -o -name '*.txt' \) -print
...print the names of all files that
...end in ".c" or ".txt".
./proj/fall.89/play.c
./proj/fall.89/referee.c
./proj/fall.89/player.c
./rock/guess.c
./rock/play.c
./rock/player.c
./rock/referee.c
./stty.txt
./tset.txt
./mail.txt
$ _
55/69
Respaldo de archivos
● tar● cpio● dump/restore
56/69
cpio, tar y dump/restore
● Hay veces que se requiere guardar archivos a medios de almacenamiento secundario– Diariamente, semanalmente o mensualmente
– Para transportar información entre computadoras que no están en red
– Para tener un respaldo extra
● cpio: almacena estructuras de directorios en un volumen de backup simple. Es útil para almacenar pequeñas cantidades de datos, no así para volúmenes grandes de datos
● tar: guarda estructuras de directorios en un volumen simple de backup. Está diseñado para guardar archivos en cinta (tape backup). Tampoco es bueno para almacenar volúmenes grandes de datos
● dump/restore: guarda directorios a múltiples volúmenes de backup. Especialmente útil para hacer respaldos totales o incrementales
57/69
cpio
Utility: cpio -ov
cpio -idtu patterns
cpio -pl directory
● -o toma una lista de nombres desde la entrada estándar y crea un archivo con formato cpio con el backup de los mismos
● -v hace que se muestre el nombre de los archivos mientras son copiados
● -i lee un archivo con formato cpio desde la entrada estándar y recrea todos los archivos contenidos dentro
● -d causa que los directorios se creen si son necesarios● -t causa que una tabla de contenidos sea mostrada en vez de
ejecutar una copia
58/69
cpio
$ ls -lG *.txt ... lista de archivos a respaldar
-rw-rw-r-- 1 angelv 101 Jun 18 12:43 animals (copy).txt
-rw-rw-r-- 1 angelv 101 Jun 18 12:43 animals.txt
-rw-rw-r-- 1 angelv 16 Jun 18 10:26 archivo1.txt
-rw-rw-r-- 1 angelv 222 Jun 18 10:52 grepfile2.txt
-rw-rw-r-- 1 angelv 533 Jun 15 08:12 grepfile.txt
-rw-rw-r-- 1 angelv 89 Jun 18 14:56 lady1.txt
-rw-rw-r-- 1 angelv 82 Jun 18 14:57 lady2.txt
-rw-rw-r-- 1 angelv 160 Jun 18 14:58 lady3.txt
-rw-rw-r-- 1 angelv 185 Jun 18 13:52 sortfile (copy).txt
-rw-rw-r-- 1 angelv 185 Jun 18 13:52 sortfile.txt
59/69
cpio
$ ls *.txt | cpio -ov > backup ... guardar en backup
animals (copy).txt
animals.txt
archivo1.txt
grepfile2.txt
grepfile.txt
lady1.txt
lady2.txt
lady3.txt
sortfile (copy).txt
sortfile.txt
5 blocks
60/69
cpio
$ ls -lG backup ... examinar backup
-rw-rw-r-- 1 angelv 2560 Jun 18 16:29 backup
$ rm *.txt ... borrar los archivos originales
$ ls -lG *.txt
ls: cannot access *.txt: No such file or directory
$ cpio -idv < backup ... restaurar los archivos
animals (copy).txt
animals.txt
archivo1.txt
grepfile2.txt
grepfile.txt
lady1.txt
lady2.txt
lady3.txt
sortfile (copy).txt
sortfile.txt
5 blocks
61/69
tar
● Fue diseñada para mantener archivos en cintas magnéticas
tar -cfrtuvxz [tarFileName] fileList
● -c crea un archivo con formato tar● -f seguida de un nombre de archivo, especifica el destino del
archivo tar● -v causa una salida detallada● -x option allows you to extract named files● -t permite generar una tabla de contenidos● -r realiza un “append” al archivo de respaldos● -u realiza un “append” únicamente de los archivos recientemente
modificados● -z filtra el respaldo a través de gzip para comprirlo y descomprimirlo
62/69
tar
$ tar -cvf tarfile .
./
./sortfile (copy).txt
./lady2.txt~
./subdirectorio/
./subdirectorio/archivoTexto.txt
./subdirectorio/archivoPoemas.txt
./subdirectorio/code.txt
./subdirectorio/holaMundo.txt
./subdirectorio/profesores.txt
tar: ./tarfile: file is the archive; not dumped
./grepfile2.txt~
./animals.txt
./lady2.txt
./animals.txt~
./sortfile.txt
./lady1.txt~
./lady3.txt~
./animals (copy).txt
./grepfile2.txt
./archivo1.txt
./lady3.txt
./sortfile.txt~
./grepfile.txt~
./grepfile.txt
./lady1.txt
./archivo1.txt~
./backup
63/69
tar
$ ls -lG tarfile
-rw-rw-r-- 1 angelv 30720 Jun 18 16:49 tarfile
angelv@angelv-Satellite-P70:~/docsGNUlinux$ tar -tvf tarfile
drwxrwxr-x angelv/angelv 0 2016-06-18 16:49 ./
-rw-rw-r-- angelv/angelv 185 2016-06-18 16:44 ./sortfile (copy).txt
-rw-rw-r-- angelv/angelv 0 2016-06-18 14:56 ./lady2.txt~
...
-rw-rw-r-- angelv/angelv 0 2016-06-18 15:49 ./subdirectorio/holaMundo.txt
-rw-rw-r-- angelv/angelv 0 2016-06-18 15:49 ./subdirectorio/profesores.txt
...
-rw-rw-r-- angelv/angelv 0 2016-06-18 13:50 ./sortfile.txt~
-rw-rw-r-- angelv/angelv 531 2016-06-15 08:10 ./grepfile.txt~
...
-rw-rw-r-- angelv/angelv 0 2016-06-18 10:26 ./archivo1.txt~
-rw-rw-r-- angelv/angelv 2560 2016-06-18 16:29 ./backup
64/69
tar
$ tar -rvf tarfile nuevoArchivoTar.txt
nuevoArchivoTar.txt
$ tar -tvf tarfile
drwxrwxr-x angelv/angelv 0 2016-06-18 16:49 ./
-rw-rw-r-- angelv/angelv 185 2016-06-18 16:44 ./sortfile (copy).txt
-rw-rw-r-- angelv/angelv 0 2016-06-18 14:56 ./lady2.txt~
...
-rw-rw-r-- angelv/angelv 0 2016-06-18 15:49 ./subdirectorio/holaMundo.txt
-rw-rw-r-- angelv/angelv 0 2016-06-18 15:49 ./subdirectorio/profesores.txt
...
-rw-rw-r-- angelv/angelv 0 2016-06-18 13:50 ./sortfile.txt~
-rw-rw-r-- angelv/angelv 531 2016-06-15 08:10 ./grepfile.txt~
...
-rw-rw-r-- angelv/angelv 0 2016-06-18 10:26 ./archivo1.txt~
-rw-rw-r-- angelv/angelv 2560 2016-06-18 16:29 ./backup
-rw-rw-r-- angelv/angelv 6 2016-06-18 16:59 nuevoArchivoTar.txt
65/69
Actividad
● Realizar el respaldo incremental de toda la información de un directorio dado. Los archivos que se respaldarán serán archivos .txt que contengan un número de 10 líneas o más, o que tengan en su texto más de 10 veces la palabra importante.
66/69
Términos/temas importantes
76/69
Revisar
● Glass, G., 2006. Linux for programmers and users. Pearson Prentice Hall, Upper Saddle River, NJ. Chapter 4 review.
77/69
Fuente
● Glass, G., 2006. Linux for programmers and users. Pearson Prentice Hall, Upper Saddle River, NJ.
78/69