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

来源:互联网 发布:儿童编程软件scratch 编辑:程序博客网 时间:2024/04/29 21:08
[cpp] view plaincopyprint?
  1. #!/bin/bash  
  2.   
  3. echo "##### 方法 1 #####"  
  4. while read line1  
  5. do  
  6.     echo $line1  
  7. done < $1  
  8.   
  9. echo "##### 方法 2 #####"  
  10. cat $1 | while read line2  
  11. do  
  12.     echo $line2  
  13. done  
  14.   
  15. echo "##### 方法 3 #####"  
  16. for line3 in $(<$1)  
  17. do  
  18.     echo $line3  
  19. done  

运行结果
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设置为换行符来达到逐行读取的功能.
[cpp] view plaincopyprint?
  1. IFS=$'\n'  
  2.   
  3. echo "##### 方法 3 #####"  
  4. for line3 in $(<$1)  
  5. do  
  6.     echo $line3  
  7. done 
0 0
原创粉丝点击