如何用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.

相关内容