假設 $file 的變數值是一個檔案名稱,該檔案內容為:
a 1
b 2
c 3
d 4
e 5
則以下方式可以將該檔案一行一行讀入,並將讀入的每一行存在 $line 變數裡面:
Method 1
Code:
number=0
while read -r line
do
number=$(($number + 1))
done < <(cat $file)
echo "# of lines = $number"
Output:
# of lines = 5
Note:
除了 cat $file 以外,也可以使用其他指令,不一定要從檔案讀入。
Method 2
Code:
number=0
while read -r line
do
number=$(($number + 1))
done < $file
echo "# of lines = $number"
Output:
# of lines = 5
Method 3
Code:
number=0
exec 9< $file
while read -u 9 -r line
do
number=$(($number + 1))
done
echo "# of lines = $number"
Output:
# of lines = 5
Note:
exec 後面的數字是 descriptor 代號,和 read -u 用一樣的就可以了。
Method 4
Code:
number=0
cat $file | while read -r line
do
number=$(($number + 1))
done
echo "# of lines = $number"
Output:
# of lines = 0
Note:
最後得出來的結果會是 0 。
0 意見:
張貼留言