The shell reads the file contents line by line

Read file content line by line in shell

1. Introduction to Grammar

#!/bin/bash
<<EOF
	shell 中逐行读取文件内容的语法如下所示。
	这里虽然很简单,但是再配合上其他的工具,如sed,awk,tr等可以获取到很多信息,因此使用起来特别方便
EOF
while read LINE
do
	#记录行数
	let count++
	#打印行号及其内容
	echo "$count $LINE"
done < $File_name

The method of reading files in shell scripts is much more convenient than other languages, which is one of the reasons why I suddenly like shell scripts. It's really easy to use. Using shell scripts can do more with less.

2. Examples

Examples are as follows:

#########################################################################
# File Name: readFileLineByLine.sh
# Author: sun
# mail: [email protected]
# Created Time: 2020年03月01日 星期日 10时38分14秒
#########################################################################
#!/bin/bash
if [ $# -ne 1 ];
then
	echo "Usage : $0 File_name"
	exit
fi

#获取文件名
File_name=$1
count=0

while read LINE
do
	#记录行数
	let count++
	#打印行号及其内容
	echo "$count $LINE"
done < $File_name

#打印读取的行数
echo "Total $count lines read from ${File_name}."
#换行符不好使?????
echo "\n\n\n\n\n\n\n\n"
#退出
exit 0

81 original articles published · Liked 69 · Visitors 50,000+

Guess you like

Origin blog.csdn.net/s2603898260/article/details/105525357