Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 如何用Shell逐行读取文件

在学习Linux shell scripts时,一个最常见的错误就是用for(for line in $(cat file.txt) do …)循环逐行读取文件。下面的例子可以看出这样做的结果。 文件file.txt内容: cat file.txt This is the row No 1; This is the row No 2; This is the row No 3.  用for循环的例子: for line in $(cat file.txt); do echo $line; done This is the row No 1; This is the row No 2; […] 显然这并不是我们想要的效果。解决方案是采用带内部读取的while循环。 while循环是用来逐行读取文件最恰当且最简单的方法: while read line; do echo $line; done < file.txt This is the row No 1; This is the row No 2; This is the row No 3.