Bienvenida e Introducción
Todo lo que aprenderás para programar en Bash Shell
Componentes de Linux, Tipos de Shell y Comandos de información
Bash scripting
Crear nuestro primer Script
Ejecutar nuestro script con un nombre único
Programación Shell Básica
Declaración de Variables y Alcance en Bash Shell
Tipos de Operadores
Script con Argumentos
Sustitución de Comandos en variables
Debug en Script
Reto 1
Script Interactivos
Capturar información usuario
Expresiones Regulares
Validar información
Paso de parámetros y opciones
Descargar información de Internet
Reto 2
Condicionales
Sentencias If/Else
Reto 3
If Anidados
Expresiones Condicionales
Sentencias Case
Iteración
Arreglos
Sentencia for loop
Sentencia while loop
Loop Anidados
Break y continue
Menú de Opciones
Reto 4
Archivos
Archivos y Directorios
Escribir dentro de archivos
Leer Archivos
Operaciones Archivos
Reto 5
Empaquetamiento
Empaquetamiento TAR, GZIP y PBZIP 2
Respaldo Empaquetado con clave
Transferir información red
Reto 6
Funciones
Crear funciones y Paso de Argumentos
Funciones de instalar y desinstalar postgres
Funciones sacar y restaurar respaldos en postgres
Reto 7
Cierre del curso
Cierre
You don't have access to this class
Keep learning! Join and start boosting your career
File manipulation is an essential skill in system administration and management. Reading files is a common task that we can perform in different ways in an Ubuntu server environment. Although in the previous classes we learned how to write a file, this time we will focus on reading it using various methods. So feel inspired and discover these methods together with us.
cat
command to read a file?The cat
command is a versatile and simple option for reading files in Linux. This command can not only show us the contents of a file in the terminal, but it can also join multiple files.
Example of use:
cat filename.txt
This command will display the entire contents of the file on the command line. It is important to keep in mind that cat
is ideal for small files, since in very large files it may be impractical due to the volume of information displayed.
Storing the contents of a file in a variable allows for further manipulation or processing. To accomplish this, we will use a combination of the cat
command with the assignment of a variable in Bash.
Example of variable assignment:
value=$$(cat filename.txt)echo $value
In this case, the contents of filename.txt
are stored in the variable value
, which can then be printed or manipulated as desired.
while
?Sometimes, it is necessary to read a file line by line, such as when we need to analyze each line individually or look for specific patterns. For this, we will use a while
loop in combination with the special variable IFS
(Internal Field Separator).
IFS=''while read -r line; do echo "$line"done < file_filename.txt
IFS
The IFS
is crucial for keeping whitespace at the beginning or end of lines. Without it, these could be trimmed, which could affect the integrity of the data we are reading.
IFS
variable?Modifying the IFS
variable can change the way lines are interpreted and separated. By setting IFS
to empty (''
), we ensure that no white space is lost during reading. When experimenting with IFS
elimination, you will notice that spaces at the beginning or end of lines may disappear, which is not always desirable.
To test reading files, let's assume we have a file named test.txt
and we want to use our commands to read it in different ways:
Use cat
to display the entire file:
cat test.txt
Store the content in a variable and display it:
content=$(cat test.txt)echo $content
Read the file line by line respecting spaces:
IFS=''while read -r line; do echo "$line"done < test.txt
Through practice and rehearsal of these methods, you will be able to tackle reading files efficiently in varied functions that might require analysis or data processing. Continue to explore and develop your file handling skills in Linux!
Contributions 16
Questions 1
Un poquito digerido para los que se puedan perder en el qué pasa aquí:
\
IFS=
IFS= read linea
Que tiene dos partes:
read linea < ruta_al_archivo
Esta sintaxis es la redirección de entrada estándar, o sea que le estoy pasando a read que lea como si fuera la entrada interactiva, pero directamente toma el archivo
Admiro el esfuerzo del profesor por tratar de ser elocuente y sacar el curso, pero en esta clase se hizo bolas muy feo. Me da la sensación de que copió el código de otro monitor con notas porque explico poco cuando mucho, y confundir un signo de pesos con una S mayúscula es una cosa muy extraña. Este curso necesita actualizarse. Cumple su propósito pero podría mejorar mucho.
Hola… saludos.
# ! /bin/bash
# Programa para leer un archivo
# Author Diego Beltran histagram @diegodevelops
echo "Leer archivoss"
cat $1
echo -e "\nAlmacenar valores en un avariable"
valorCat=`cat $1`
echo "$valorCat"
#se usa variable especial IFS (internal file separator) evitar recortes de espacios en blanco
echo -e "\nLeer archivos linea por linea utilizando while "
while IFS= read linea
do
echo "$linea"
done < $1```
Queda de la siguiente forma:
# ! /bin/bash
# Programa para ejemplificar como se lee en un archivo
# Autor Jose Suarez
echo "Leer en un Archivos"
cat $1
echo -e "\nAlmacenar valores en un avariable"
valorCat=`cat $1`
echo "$valorCat"
#se usa variable especial IFS (internal field separator) evitar recortes de espacios en blanco
echo -e "\nLeer archivos linea por linea utilizando while "
while IFS= read linea
do
echo "$linea"
done < $1
Existen 3 métodos:
# ! /bin/bash
# Programa para ejemplificar cómo se lee en un archivo
# Autor: Juan Manuel
echo "Leer en un archivo"
#Primer método
echo -e "\nLeer directamente todo el archivo"
cat $1
#Segundo método
echo -e "\nAlmacenar los valores en una variable"
valorCat=`cat $1`
echo "$valorCat"
#Tercer método
#Se utiliza la variable especial IFS (Internal File Separator) para evitar que los espacios en blanco se recorten
echo -e "\nLeer archivos línea por línea utilizando while"
while IFS= read linea
do
echo "$linea"
done < $1
podemos ir copiando y dando enter hasta las lineas que queramos enviar al argumento y se finaliza con control+c
echo “Escribir en un archivo”
lectura = $(cat >> $1)
Muchas gracias profe
No entiendo porque cuando coloca un comando en el script a veces usa el formato ls a veces $(ls) o a veces simplemento lo coloca así sin más ¿cuál es la diferencia, cuando se usa uno u otro?
Un ejemplo que explica para que sirve la variable IFS:
IFS
La sustitución de comandos permite usar la salida de un comando como si fuera el valor de una variable
La sintaxis antigua es : variable='comando`
pero actualmente se prefiere usar : variable=$(comando)
A estas alturas ya nadie se queja del “tema”
hola buenas tardes no es nada facil para mi hacer las comillas dobles , lo hice con control y la tecla + , si sabes otra forma coenta por favor
Listo y entendido
#!/bin/bash
# Reading a file
cat $1
# Saving the read response in a variable
cat_response=`cat $1`
echo "$cat_response"
# Reading a file line by line with IFS to read also the blank spaces
while IFS= read line
do
echo "$line"
done < $1
Want to see more contributions, questions and answers from the community?