Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

如何在 Shell 中逐行讀取檔案

學 Linux shell 腳本時,最常見的錯誤莫過於用 for 迴圈(for line in $(cat file.txt))來逐行讀檔。先看它會產生什麼結果。

假設 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