2025年3月28日 星期五 甲辰(龙)年 月廿七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Shell

SHELL 读取文件的每一行内容并输出

时间:03-06来源:作者:点击数:44

假设读取的文件为当期目录下的 test.txt 文件,内容如下:

  • Google
  • Runoob
  • Taobao

实例 1

  • #!/bin/bash
  • while read line
  • do
  • echo $line
  • done < test.txt

执行输出结果为:

  • Google
  • Runoob
  • Taobao

实例 2

  • #!/bin/bash
  • cat test.txt | while read line
  • do
  • echo $line
  • done

执行输出结果为:

  • Google
  • Runoob
  • Taobao

实例 3

  • for line in `cat test.txt`
  • do
  • echo $line
  • done

执行输出结果为:

  • Google
  • Runoob
  • Taobao

for 逐行读和 while 逐行读是有区别的,如:

  • $ cat test.txt
  • Google
  • Runoob
  • Taobao
  • $ cat test.txt | while read line; do echo $line; done
  • Google
  • Runoob
  • Taobao
  • $ for line in $(<test.txt); do echo $line; done
  • Google
  • Runoob
  • Taobao

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门