Iterating Through File Lines with "for"
When working with files in Bash, one of the most common tasks is to iterate through the lines of a file and perform some operation on each line. The "for" loop provides a straightforward way to accomplish this.
Reading File Lines with "for"
Here's the basic syntax for iterating through the lines of a file using the "for" loop:
for line in $(cat filename); do
## Perform actions on each line
echo "$line"
done
In this example, the cat filename
command reads the contents of the file and passes each line to the "for" loop. The loop variable line
will hold the current line, and you can perform any desired operations on it within the loop body.
Alternatively, you can use the readlines
function to read the file line by line:
while read -r line; do
## Perform actions on each line
echo "$line"
done < filename
This approach is often preferred, as it can handle files with trailing newlines more reliably.
Accessing Line Data
Once you have the current line within the "for" loop, you can access and manipulate the line data in various ways. For example, you can split the line into individual fields using the IFS
(Internal Field Separator) variable:
IFS=$'\n' ## Set the field separator to newline
for line in $(cat filename); do
IFS=$' \t' ## Reset the field separator to space and tab
read -ra fields <<< "$line"
echo "Field 1: ${fields[0]}"
echo "Field 2: ${fields[1]}"
done
This example first sets the field separator to newline to read each line as a separate item. Then, within the loop, it resets the field separator to space and tab, allowing it to split the line into individual fields using the read
command.
By combining the "for" loop with line data manipulation techniques, you can create powerful scripts that automate file-based tasks, such as data extraction, transformation, or reporting.