shell脚本-----按行读取文件

来源:互联网 发布:编辑书的软件 编辑:程序博客网 时间:2024/03/29 13:00
按行读取文件
#!/bin/bashecho "##### 方法 1 #####"while read line1doecho $line1done < $1echo "##### 方法 2 #####"cat $1 | while read line2doecho $line2doneecho "##### 方法 3 #####"for line3 in $(<$1)doecho $line3done

运行结果
snail@ubuntu:5.read-line$ cat file.bin 
hello world
this is 1
this is 2
this is 3
snail@ubuntu:5.read-line$ ./read-line.sh file.bin 
##### 方法 1 #####
hello world
this is 1
this is 2
this is 3
##### 方法 2 #####
hello world
this is 1
this is 2
this is 3
##### 方法 3 #####
hello
world
this
is
1
this
is
2
this
is
3

使用for读取时,自动按空格作为间隔符。
如果输入文本每行中没有空格,则line在输入文本中按换行符分隔符循环取值.

如果输入文本中包括空格或制表符,则不是换行读取,line在输入文本中按空格分隔符或制表符或换行符特环取值.

可以通过把IFS设置为换行符来达到逐行读取的功能.
IFS=$'\n'echo "##### 方法 3 #####"for line3 in $(<$1)doecho $line3done


原创粉丝点击