Detailed explanation of the method of shell loop reading each line in the file

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 linethe command is used to read each line in the file and store it in linea variable. < filenameRepresents 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 whilea loop to read example.txteach line in the file and echooutput 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. forThe loop assigns each line in the string to linea 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 fora loop to read example.txteach line in the file and echooutput 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.txtfile 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.txtfile 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.

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/132809359