2017-07-15 86 views
0

我用bash腳本逐行讀取文件時遇到了問題。下面是該腳本:如何在Bash腳本中逐行讀取文件?

#!/bin/bash 

file="cam.txt" 

while IFS=: read -r xf1 xf2 xf3 
do 
    printf 'Loop: %s %s %s\n' "$xf1" "$xf2" "$xf3" 
    f1=$xf1 
    f2=$xf2 
    f3=$xf3 
done < $file 
printf 'After: %s %s %s\n' "$f1" "$f2" "$f3" 

這裏是cam.txt

192.168.0.159 
554 
554 

這裏是輸出:

Loop: 192.168.0.159 
Loop: 554 
Loop: 554 
After: 554 

可能是什麼問題呢?

+0

顯示你的文件的樣本。 – Mat

+0

我加了。感謝您的關注@Mat – voyvoda

+1

現在還不清楚你想要做什麼。輸出與您的代碼和輸入文件相同。請更詳細地解釋你想要達到的目標。 – Mat

回答

-1

你的代碼讓我相信你想讓每一行變成一個變量。

試試這個腳本(我知道這是可以做到更輕鬆,更漂亮,但這是一個簡單易讀的例子):

#!/bin/bash 
file="cam.txt" 

while read -r line 
do 
    printf 'Line: %s\n' "$line" 

    current=$line 
    last=$current 
    secondlast=$last 

    printf 'Loop: %s %s %s\n' "$current" "$last" "$secondlast" 
done < $file 

printf 'After: %s %s %s\n' "$current" "$last" "$secondlast" 

簡單的版本:

{ read -r first; read -r second; read -r third; } <cam.txt 
printf 'After: %s %s %s\n' "$first" "$second" "$third"