Linux/UNIX: Bash Read a File Line By Line

In the bash shell, you can read a file line by line using a while loop and the read command. The read command reads a line of text from the standard input and splits it into fields, which can be assigned to variables.

Here’s a simple example that reads a file line by line and prints each line to the standard output:

#!/bin/bash

filename="file.txt"

while read -r line; do
echo "$line"
done < "$filename"

In this example, the read command reads a line of text from the input file file.txt and assigns it to the line variable. The -r option is used to prevent the read command from interpreting backslashes as escape characters. The done keyword signals the end of the loop, and the < "$filename" part at the end of the loop redirects the input to the file file.txt.

If you want to process each line of the file as a separate task, you can use the loop to call a function or run a command for each line. For example:

#!/bin/bash

filename="file.txt"

process_line() {
echo "Processing line: $1"
}

while read -r line; do
process_line "$line"
done < "$filename"

In this example, the loop calls the process_line function for each line of the input file, passing the line as an argument. The function can then perform any desired processing on the line. (https://tokyosmyrna.com/)

Leave a Comment