当前位置:首页 > 开发 > 系统架构 > shell > 正文

shell编程--按行读取文件中数据

发表于: 2014-05-18   作者:无量   来源:转载   浏览:
摘要: #!/bin/sh echo "###### method 1 ######" while read line1 do echo $line1 done < $1 echo "###### method 2 ######" cat $1 | while read line2 do echo $line2
#!/bin/sh
echo "######   method 1  ######"
while read line1
do
    echo $line1
done < $1

echo "######   method 2  ######"
cat $1 | while read line2
do
    echo $line2
done

echo "######   method 3  ######"
for line3 in $(<$1)
do
    echo $line3
done



文件testRead.txt内容
[root@localhost Desktop]# cat testRead.txt
why life is more unhappniess than happy
you must work more hardly
fell lonely
I should more happy
[root@localhost Desktop]# ./read.sh /root/Desktop/testRead.txt
######   method 1  ######
why life is more unhappniess than happy
you must work more hardly
fell lonely
I should more happy
######   method 2  ######
why life is more unhappniess than happy
you must work more hardly
fell lonely
I should more happy
######   method 3  ######
why
life
is
more
unhappniess
than
happy
you
must
work
more
hardly
fell
lonely
I
should
more
happy
[root@localhost Desktop]#




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

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

可以通过把IFS设置为换行符来达到逐行读取的功能.

  
 IFS=$'\n'  
      
    echo "##### 方法 3 #####"  
    for line3 in $(<$1)  
    do  
        echo $line3  
    done  

shell编程--按行读取文件中数据

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号