我們通過一些實例,來進一步了解使用輸入重定向從文件讀取內容的一些方法。
在 Shell 腳本中我們針對某一個代碼塊使用輸入重定向,請看下面的實例,我們在腳本中的一個代碼塊使用重定向讀取文件的內容。
#! /bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 FILEPATH"
exit
fi
file=$1
{
read line1
read line2
} < $file
echo "First line in $file is:"
echo "$line1"
echo "Second line in $file is:"
echo "$line2"
exit 0
上述腳本的運行結果:
運行結果
有時我們可能需要逐行地讀取一個文件中的內容,并對每一行進行特定的處理,這時該如何操作?下面的示例,將使用 while 循環與重定向結合使用來逐行地讀取文件的內容。
#! /bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 FILEPATH"
exit
fi
filename=$1
count=0
while read LINE
do
let count++
echo "$count $LINE"
done < $filename
echo -e "\nTotal $count lines read."
exit 0
上述實例的運行結果將類似如下所示:
運行結果
當然我們也可以使用 until 循環來實現與上述實例同樣的功能:
#! /bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 FILEPATH"
exit
fi
filename=$1
count=0
until ! read LINE
do
let count++
echo "$count $LINE"
done < $filename
echo -e "\nTotal $count lines read."
exit 0
上述實例的運行結果將類似如下所示:
運行結果
上述實例與前一個實例的唯一區別就是語句 “until ! read LINE”。
我們再看一下使用 if 語句結合重定向讀取文件的內容:
#! /bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 FILEPATH"
exit
fi
filename=$1
count=0
if true; then
read LINE
let count++
echo "$count $LINE"
fi < $filename
echo -e "\nTotal $count lines read."
exit 0
上述實例的運行結果將類似如下所示:
運行結果
本文參考自 《Linux Shell命令行及腳本編程實例詳解 》