2016-03-03 18 views
1

我已經看到的文章'for' loop。它會像空間,製表符或換行符一樣發生空白。爲了得到這個問題的騎我有以下命令的額外的行:在'for'循環中用空格讀取完整行,具有多個輸入文件的選項卡

IFS=$'\n' 

但是當我嘗試來解決以下細節上面的場景(我有兩個文件:「input1.txt」'input.txt的'我的當前目錄):

bash命令:

bash script.sh 'input*' 

下面是'爲' 在script.sh循環塊

for line in $(cat $1) 
... 
... 
done; 

我上執行以下錯誤:

cat: input1.txt input.txt*: No such file or directory 

注:我想這兩個文件input1.txt and input.txt

+1

從文件中讀取:HTTP://mywiki.wooledge .org/BashFAQ/001 –

+0

錯誤消息不是由消息中的命令生成的。請提出更準確的問題陳述。 – rici

回答

2

通過重置$IFS,禁用詞分裂,將導致該模式的擴張$1被視爲單獨的文件名。這是做這個權利方式的另一個原因。但首先讓我們假設您真的想將模式傳遞給您的腳本,而不是僅使用bash script.sh input*讓shell將模式展開爲腳本的文件列表。然後,你的循環應該是這樣

cat $1 | while IFS= read -r line; do 
    ... 
done 

但是,如果任何匹配的文件本身有空格在其名稱,這將不起作用;與input a.txtinput b.txt,$1將展開爲字input,a.txt,inputb.txt。相反,你應該讓殼做的擴展,並通過每個匹配的文件作爲單獨的參數:

bash script.sh input* 

,並在你的腳本:

for f in "[email protected]"; do 
    while IFS= read -r line; do 
     ... 
    done < "$f" 
done 
相關問題