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

shell脚本读取文件的方法

时间:09-01来源:作者:点击数:26

第一种:

  • #!/bin/bash
  • while read line
  • do
  • echo $line
  • done < filename

示例:要读取的文件我这里四test.txt

首先vi新建一个文件.sh结尾

  • [root@uc-crawl01 test]# vi read_file.sh

然后照着上面的方法编写脚本

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

test.txt里面的内容

  • [root@uc-crawl01 test]# cat test.txt
  • 123
  • 456
  • 789

这就是读取结果,./read_file.sh.sh就能执行了,在执行之前需要加执行权限

  • [root@uc-crawl01 test]# ./read_file.sh
  • -bash: ./read_file.sh: Permission denied
  • [root@uc-crawl01 test]# chmod 777 read_file.sh
  • [root@uc-crawl01 test]# ./read_file.sh
  • 123
  • 456
  • 789

第二种:

  • #!/bin/bash
  • cat filename | while read line
  • do
  • echo $line
  • done

第三种:

  • #!/bin/bash
  • for line in `cat filename`
  • do
  • echo $line
  • done

还有一种以文件描述符方式的,但是我没怎么用过就不写了,以上三种就是比较常用的shell读文件的方法

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