How to use read command and while loop In Linux
We can use the read command to read the contents of a file line by line. We use the -r argument to the read command to avoid any backslash-escaped characters.
#!usr/bin/env bash file="temp.txt" while read -r line; do echo -e "$line\n" done <$file
In the following example, we can see that we have an iteration over a file line by line and we store the contents of a single line in the variable “line“. The file name is stored in the variable file and this can be customized as per requirements. You can run the script using the following command (Here filereader.sh can be any name you give to your script).
bash filereader.sh
We use the read command with -r argument to read the contents without escaping the backslash character. We read the content of each line and store that in the variable line and inside the while loop we echo with a formatted -e argument to use special characters like \n and print the contents of the line variable.
The file can be also inputted by parsing it as a positional parameter.
bash filereader.sh filename
The filename can be any file you want to read the contents of. You need to change the script where the file variable has been declared.
file=$1
This will take the first parameter after the script name as the filename to be used in the script. Hence we can make the script dynamically change the file as per the input given.
Bash Scripting – How to read a file line by line
In this article, we are going to see how to read a file line by line in Bash scripting.
There might be instances where you want to read the contents of a file line by line using a BASH script. In this section, we will look at different ways to do just that. We will use BASH commands and tools to achieve that result. We make use of the read and cat commands, for loops, while loops, etc to read from the file and iterate over the file line by line with a few lines of script in BASH.