歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> 如何用Shell逐行讀取文件

如何用Shell逐行讀取文件

日期:2017/3/1 10:24:27   编辑: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.

Copyright © Linux教程網 All Rights Reserved