
while
我正在bash 中嘗試這個簡單的循環。
我的文字文件
# cat test.txt
line1:21
line2:25
line5:27
These are all on new line
我的腳本
# cat test1.sh
while read line
do
awk -F":" '{print $2}'
done < test.txt
輸出
# ./test1.sh
25
27
輸出不列印第一行$2
值。有人可以幫我理解這個案例嗎?
答案1
你不需要那個循環:
$ awk -F ':' '{ print $2 }' test.txt
21
25
27
awk
將逐行處理輸入。
透過循環,read
將獲得文件的第一行,該行由於未使用/輸出而丟失。然後,它將awk
接管循環的標準輸入並讀取檔案中的其他兩行(因此循環將只執行一次迭代)。
你的循環,註解:
while read line # first line read ($line never used)
do
awk -F ':' '{ print $2 }' # reads from standard input, which will
# contain the rest of the test.txt file
done <test.txt
答案2
我能夠透過添加來修復您的程式碼echo
。原因已描述那裡,詢問為什麼它會列印其他兩個值。
while read line;
do
echo "$line" | awk -F":" '{print $2}'
done < test.txt
答案3
while IFS=":" read z x; do
echo $x;
done<test.txt
或者
sed "s/^.*://g" test.txt