I have a file with this content:
Hola qué tal
Yo \t muy bien
Un placer.
I want to read it line by line, saving the value of each line in a variable to process it.
That is, I want:
- Read the first line.
- Carry out the assignment of the value "Hello how are you" to the variable $linea.
- Do things with
$linea
. - Read the second line.
- Assign the value "I \t very well" to
$linea
.
And so on.
Use
while ... do ... done < fichero
with some nuance:Which is explained as:
IFS=''
(orIFS=
) prevents leading or trailing space (space or tab) characters from being removed.-r
prevents the backslash (\
) from being interpreted as a special character.|| [[ -n $linea ]]
prevents the last line from being ignored if it doesn't end with\n
(since itread
returns a non-zero exit when it encounters an EOF). Theoretically, a line should end with\n
and is defined by POSIX as follows : Sequence of zero or more characters other than a newline\n
followed by a newline character . However, it may be the case that a file has been written in which the last line does not contain it; with this addition, that line would also be processed.So, in your file we would have this output:
Let's see what would happen if we removed any of the checks:
Without
IFS=''
: leading and trailing spaces are removed.Sin
-r
enread
: the backslash is interpreted.Sin
|| [[ -n $linea ]]
: a hypothetical last line not ending in\n
would not be read:Given the previous file, if we add a new series of characters without
\n
ending:We observe that its content appears in this way:
When we read, this last line is not processed:
References:
cat file | while IFS= read -r line; do … done