2012-03-11 55 views
3

我正在處理一個腳本,該腳本從csv文件中提取數據,操作數據,然後詢問用戶更改是否正確。問題是你似乎無法在正在讀取文件的while循環中執行讀命令。測試腳本包含在下面,注意一個in文件需要被創建,只要它沒有被真正使用。這只是我正在研究的更大腳本的摘錄。我重新編碼它使用似乎工作的數組,但想知道是否有任何解決方法?我一直在閱讀幾個bash指南,並閱讀手冊頁,並沒有找到答案。提前致謝。Bash在讀取文件的循環內讀取

#!/bin/bash 
######### 
file="./in.csv" 
OLDIFS=$IFS 
IFS="," 
######### 

while read custdir custuser 
do 
    echo "Reading within the loop" 
    read what 
    echo $what 
done < $file 

IFS=$OLDIFS 
+0

您可能會發現'awk'成爲你試圖做一個更好的選擇。 – 2012-03-11 01:52:38

回答

7

您可以擺弄文件句柄,以便您仍然可以訪問舊的標準輸入。例如,該文件qq.sh將讀取本身和使用read循環打印每行,也問你一個問題,每行後:

while read line 
do 
    echo " Reading within the loop: [$line]" 
    echo -n " What do you want to say? " 
    read -u 3 something 
    echo " You input: [$something]" 
done 3<&0 <qq.sh 

它通過先保存標準輸入做到這一點(文件句柄0)進入文件處理3與3<&0,然後使用read -u <filehandle>變種從文件句柄3.一個簡單的成績單爲:

pax> ./qq.sh 
    Reading within the loop: [while read line] 
    What do you want to say? a 
    You input: [a] 
    Reading within the loop: [do] 
    What do you want to say? b 
    You input: [b] 
    Reading within the loop: [echo "Reading within the loop: [$line]"] 
    What do you want to say? c 
    You input: [c] 
    Reading within the loop: [echo -n "What do you want to say? "] 
    What do you want to say? d 
    You input: [d] 
    Reading within the loop: [read -u 3 something] 
    What do you want to say? e 
    You input: [e] 
    Reading within the loop: [echo "You input: [$something]"] 
    What do you want to say? f 
    You input: [f] 
    Reading within the loop: [done 3<&0 <qq.sh] 
    What do you want to say? g 
    You input: [g] 
    Reading within the loop: [] 
    What do you want to say? h 
    You input: [h] 
pax> _ 
+0

謝謝,我正要問,如何修復它。這對小測試腳本起作用,現在將其納入實際腳本中。再次感謝。 – SoulNothing 2012-03-11 02:14:28