
我想迭代包含以下格式的日期(名為dates.txt)的檔案:
2009 08 03 08 09
2009 08 03 09 10
2009 08 03 10 11
2009 08 03 11 12
2009 08 03 12 13
2009 08 03 13 14
並將每行的每個欄位作為位置參數傳遞給另一個腳本。
即:另一個腳本是透過在命令列中輸入以下內容來執行的:
$ . the_script 2009 08 03 08 09
我努力了for i in $(./dates.txt);do echo ${i};done
但得到:
./dates: line 1: 2009: command not found
./dates: line 2: 2009: command not found
./dates: line 3: 2009: command not found
./dates: line 4: 2009: command not found
./dates: line 5: 2009: command not found
./dates: line 6: 2009: command not found
從這裡我可以看出它正在通過每條線工作,但也許在每個領域都掛斷了?
由於上述原因,我還無法弄清楚如何將讀取行作為位置參數傳遞給其他腳本。也不知道在哪裡工作?請幫忙!
答案1
也許你的意思是這樣的?
while read -d $'\n' i; do echo $i;done <./dates
while read -d $'\n' i; do . the_script $i;done <./dates
答案2
.
如果不需要採購( ),這聽起來像是一份工作xargs
:
xargs -a dates.txt -rL1 the_script
xargs
讀取一行輸入,然後將其用作指定命令的參數。預設行分隔符號是換行符。- 我們可以從其他命令將資料傳輸到它,或使用
-a
. - 由於每次呼叫腳本只使用一行,因此我們指定
-r
(如果行為空則不執行)和-L
(每次呼叫最多使用 N 行)選項。
答案3
如果腳本不在同一目錄中,請在命令中使用cat
並確保使用正確的檔案名稱路徑。如果清單是,dates.txt
則使用$(cat ./dates.txt)
.此處編輯錯字。包含 .txt
這是一個例子:
名為 的日期列表dates.txt
。
2009 08 03 08 09
2009 08 03 09 10
2009 08 03 10 11
2009 08 03 11 12
2009 08 03 12 13
2009 08 03 13 14
一個腳本的命名是lstdates.sh
為了呼應該列表中的行星。已編輯
它在內部字段分隔符號 (IFS) 的子 shell 中運行1在子 shell 之外不會更改2。
#!/bin/bash
# Listing each date as an argument for `the_script`.
# Parenthesis runs in a subshell
(
# IFS line break
IFS=$'\012'
for dates in $(cat ./dates.txt)
do
echo $(./the_script $dates)
done
)
預設情況下,IFS 將每個空格識別為欄位的結尾。IFS=$'\012'
將每個新行識別為欄位的結尾。如果每一行都用雙引號引起來,例如"2009 08 03 08 09"
,那麼預設的 IFS 將會起作用。
the_script
僅包含以下內容。
#!/bin/bash
echo $1