How to read a file line by line in a Shell script
Xiaobian to share with you how to read the file line by line in the Shell script, I believe most people still do not know how to share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
Method 1: Use Input Redirection
The easiest way to read a file line by line is to use input redirection in a while loop.
To demonstrate, create a text file named " mycontent.txt" with the following contents:
[root@localhost ~]# cat mycontent.txt This is a sample file We are going through contents line by line to understand
Create a script called "example1.sh" that uses input redirection and looping:
[root@localhost ~]# cat example1.sh #!/ bin/bash while read rows do echo "Line contents are : $rows " done
< mycontent.txt 运行结果:
How it works:
- Start the while loop and save the contents of each line in the variable "rows"
- Use echo to display the output, and the $rows variable is each line in the text file
- Use echo to display output, including custom strings and variables, and the $rows variable is each line in the text file
Tips: You can reduce the above script to a single command, as follows:
[root@localhost ~]# while read rows; do echo "Line contents are : $rows"; done < mycontent.txt
Method 2: Use cat command and pipe symbol
The second method is to use the cat command and pipe characters|, and then pipe its output as input to the while loop.
Create a script file "example2.sh" with the following contents:
[root@localhost ~]# cat example2.sh #!/ bin/bash cat mycontent.txt | while read rows do echo "Line contents are : $rows " done
Run Results:
How it works:
- Pipelines the output of the cat command as input to the while loop.
- |管道符将cat输出的内容保存在"$rows"变量中。
- Use echo to display output, including custom strings and variables, and the $rows variable is each line in the text file
Tips: You can reduce the above script to a single command, as follows:
[root@localhost ~]# cat mycontent.txt |while read rows;do echo "Line contents are : $rows";done
Method 3: Use the file name passed in as an argument
The third method appends the text file name to the end of the script when executing it by adding the $1 parameter.
Create a script file called "example3.sh" as follows:
[root@localhost ~]# cat example3.sh #!/ bin/bash while read rows do echo "Line contents are : $rows " done < $1
Run Results:
How it works:
- Start the while loop and save the contents of each line in the variable "rows"
- Use echo to display the output, and the $rows variable is each line in the text file
- Use input redirection