When you need to read each line in a file for processing in a shell script, you can use a while loop or a for loop. Both methods are described in detail below.
Method 1: Use while loop
Using a while loop is a common way to read each line in a file. The basic syntax of this method is as follows:
while read line
do
# 处理每一行的代码
done < filename
Among them, read line
the command is used to read each line in the file and store it in line
a variable. < filename
Represents reading input from a file.
Here is an example showing how to use a while loop to read each line in a file:
#!/bin/bash
filename="example.txt"
while read line
do
echo $line
done < $filename
In the above example, we use while
a loop to read example.txt
each line in the file and echo
output it to the terminal using a command.
Method 2: Use for loop
Using a for loop is also a way to read every line in a file. The basic syntax of this method is as follows:
for line in $(cat filename)
do
# 处理每一行的代码
done
Among them, $(cat filename)
the command is used to read the contents of the file into a string and use spaces or newlines to separate each line. for
The loop assigns each line in the string to line
a variable.
Here is an example showing how to use a for loop to read each line in a file:
#!/bin/bash
filename="example.txt"
for line in $(cat $filename)
do
echo $line
done
In the above example, we use for
a loop to read example.txt
each line in the file and echo
output it to the terminal using a command.
Example description
Below are two examples that demonstrate how to use a shell script to loop through each line in a file.
Example 1: Use a while loop to read each line in the file
Suppose there is a example.txt
file named with the following content:
apple
banana
orange
We can use the following shell script to read each line in the file using a while loop:
#!/bin/bash
filename="example.txt"
while read line
do
echo $line
done < $filename
Running the above script will output the following:
apple
banana
orange
Example 2: Use a for loop to read each line in the file
Let's say we have a example.txt
file called with the following content:
apple
banana
orange
We can use the following shell script to read each line in the file using a for loop:
#!/bin/bash
filename="example.txt"
for line in $(cat $filename)
do
echo $line
done
Running the above script will output the following:
apple
banana
orange
Summarize
Using while loops and for loops are both common ways to read each line in a file. The while loop is suitable for processing large files, while the for loop is suitable for processing small files. When using these two methods, you need to pay attention to the format of each line in the file so that the contents of each line can be read and processed correctly.