How to use cat and for loop In Linux
From this approach, we can read the contents of a file using the cat command and the for a loop. We use the same approach for a loop as in the while loop but we store the contents of the file in a variable using the cat command. The for loop iterates over the lines in the cat command’s output one by one until it reaches EOF or the end of the file.
Here as well we can incorporate the positional parameter as a filename. We need to replace the filename with $1 in the script.
file=$(cat $1)
This will take the file from the command line argument and parse it to the cat command to further process the script.
#!usr/bin/env bash file=$(cat temp.txt) for line in $file do echo -e "$line\n" done
Thus, from the above examples, we were able to read the contents of a file line by line in a BASH script.
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.