2014-11-24 65 views
2

我在寫一個bash腳本,創建用戶。 我想逐行讀取名稱爲text的文本文件,並在每個文件上執行一個函數。 我試過谷歌搜索了很多,但沒有任何工作爲我。 我希望用戶輸入文件的路徑,每行有一個名稱,然後我將在其上添加函數。逐行讀取名稱並在Bash腳本中對其執行某些功能

echo "Enter file path:" 
read line 
while read line 
do 
    name=$line 
    echo "Text read from file - $name" 
done < $1 

我該怎麼做? 我會很感激的一點幫助上, 問候

回答

1

有幾個微妙的東西可以幫助你的腳本。在讀取文件名之前,您應該設置IFS(內部字段分隔符),使其僅在newline處中斷。這將確保您獲得完整的文件名,如果它包含空格並且沒有被引用。讀取文件名後恢復IFS。您還需要檢查$line是否已在read之後被讀取,以確保在數據文件最後一行末尾沒有newline的情況下得到最後一行。

此外,每當你從用戶讀取一個文件名,你應該確認它是一個有效的文件名試圖從中讀取數據之前:

#!/bin/bash 

oifs=$IFS        # save internal field separator 
IFS=$'\n'        # set IFS to newline (if whitespace in path/name) 

echo -n "Enter file path/name: "  # suppress newline 
read fname        # read full-path/filename 

IFS=$oifs        # restore default IFS=$' \t\n' 

[ -r "$fname" ] || {     # validate input file is readable 
    printf "error: invalid filename '%s'\n" "$fname" 
    exit 1 
} 

while read line || [ -n "$line" ]  # protect against no newline for last line 
do 
    name=$line 
    echo "Text read from file - $name" 
done < "$fname"       # double-quote fname 

exit 0 

樣品使用/輸出:

$ bash readfn.sh 
Enter file path/name: dat/ecread.dat 
Text read from file - read: 4163419415  0  0  4163419415 0 4395.007  0 
Text read from file - read: 4163419415  0  0  4163419415 0 4395.007  0 
Text read from file - read: 4163419415  0  0  4163419415 0 4395.007  1 
Text read from file - read: 4163419415  0  0  4163419415 0 4395.007  0 
+0

非常感謝你的答案,但我只是在一個點混淆。 爲什麼你在這裏使用-r: [-r「$ fname」] || {#驗證輸入文件可讀 printf「錯誤:無效文件名'%s'\ n」「$ fname」 exit 1 } – Umair 2014-11-26 22:44:25

+0

您可以使用'-e'(是否存在),'-f'它是一個文件)等,但最具體的是'-r'(它是可讀的[它包含存在,作爲一個文件,並且具有足夠的權限來閱讀])。或者你可以把握機會,而不是測試(不推薦)。重點在於,在驗證之前,任何用戶輸入都應該被視爲**可疑**。不知道將會輸入什麼。 – 2014-11-27 00:17:18

+0

非常感謝。'|| ||這意味着OR,對嗎?對不起,這樣noob問題,但我剛剛開始.. – Umair 2014-11-27 00:24:30

0

試試這個:

echo "Enter file path:" 
read filepath 
while read line 
do 
    name="$line" 
    echo "Text read from file - $name" 
done < "$filepath" 
0

我認爲像這樣將整理你出去,給它一去。

echo "Enter file path:" 
read filename  
while read line  
do  
    name=$line 
    echo "Text read from file - $name"  
done < $filename 
+0

是的,我知道,我沒有完成我的答案,併發布了你的答案。 在Umair最初的bash腳本中,您將文件名分配給行變量,但是while循環讀取的是$ 1(最有可能未設置)。 while循環會覆蓋行變量。 – luke 2014-11-24 00:55:08