Shell脚本从文件中逐行读取内容的几种方法实例

今天小编就为大家分享一篇关于Shell脚本从文件中逐行读取内容的几种方法实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

从文件逐行读取数据的方法有两种,一种是在while循环或until循环中使用read命令,通过文件描述符一行一行的读取文件内容;另一种是在for循环中使用cat 来读取文件的内容。

”“”“”,所以他首先以空格作为分隔符来读取文件内容,因此如果使用for循环逐行读取内容,在for循环开始之前需要先修改变量IFS的值,等for循环结束后再将IFS的值改回来。

示例1:

 #!/bin/bash bak=$IFS                     #定义一个变量bak保存IFS的值 if [ $# -ne 1 ];then             #判断位置参数是否为1 echo "Usage $0 filename" exit fi if [ ! -f $1 ];then               #判断位置参数是否为文件 echo "the $1 is not a file" exit fi IFS=$'\n'                    #将环境变量IFS的值修改为换行符 for i in `cat $1`                #逐行读取文件内容并打印到屏幕 do echo $i done IFS=$bak                    #将环境变量IFS的值改回原值

示例2:如果不修改变量IFS的值,系统默认按照IFS的原值,按空格来读取文件

 #!/bin/bash if [ $# -ne 1 ];then echo "Usage $0 filename" exit fi if [ ! -f $1 ];then echo "the $1 is not a file" exit fi for i in `cat $1` do echo $i done

2.在脚本中定义代码块,使用重定向逐行读取文件内容:

示例:

 #!/bin/bash if [ $# -ne 1 ];then             #判断脚本参数是否为1 echo "Usage:$0 filename" exit 1 fi file=$1                      #将脚本参数参数赋值给变量file {                            #定义代码块,大括号{}中的代码即为代码块 read line1 read line2 } <$file                       #使用$file将代码块的标准输入指向文件$file echo "first line in $file is $line1"   #输出文件内容 echo "second line in $file is $line2" exit 2

3.使用while循环结合read命令逐行读取文件内容:

 #!/bin/bash if [ $# -ne 1 ];then echo "Usage:$0 filename" exit 1 fi file=$1 if [ ! -f $file ];then echo "the $file is not a file" exit 2 fi count=0 while read line   #使用read命令循环读取文件内容,并将读取的文件内容赋值给变量line do let count++ echo "$count $line" done <$file      #“done <$file”将整个while循环的标准输入指向文件$file echo -e "\ntotle $count lines read" exit 0

总结

以上就是Shell脚本从文件中逐行读取内容的几种方法实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 脚本专栏