2015-06-30 86 views
0

我有以下scrip,它從兩個不同的目錄中讀取文件。隨着第一組文件我做了一些東西。從另一個目錄中讀取每行的另一組文件(.txt)。現在一切正常,除了我必須包含引號才能使腳本工作。如果我不包含它們,它只會從第一個目錄中讀取文件。從兩個不同的目錄中讀取文件

這是我正在運行它

慶典move.sh 「資料/生成/工作/ generate_profiles_output/merged_profiles/profiles_ * .avro」 「刺/ MP /來電/元/文件/ *。TXT」

#!/bin/bash 

AVROFILES=$1 
FILES=$2 
#reading every avro file 
for avrofile in ${AVROFILES} 
do 

    //do some stuff with the avrofile 

    #reading the files 
    for f in $FILES 
    do 
     #reading every line in on from the file 
     while read line 
     do 

     done <"$f" 

    done 
done 
+0

'profiles_ * .a'中有一個空格。如果未加引號,則字段拆分會在空間上發生,並且在腳本開始之前發生文件擴展,從而僅保留讀取的第一個文件。 –

+0

使用雙引號是變量合理處理的事實標準。簡單的空格將會破壞你的腳本。總是引用你的變量。閱讀:http://mywiki.wooledge.org/WordSplitting – tvm

+1

每個可以在腳本中引用的變量都是*引號。這個腳本的參數被引用,所以變量擴展不能讓globs擴展正確。 –

回答

1

不通過引用圖案的外殼作爲參數;相反,選擇一個非文件分隔符來區分這兩組文件。 (在這裏,我使用:::,這GNU parallel使用類似的目的。)

$ bash move.sh profile/generate/work/generate_profiles_output/merged_profiles/profiles_ *.avro ::: prod/mp/incoming/meta/files/*.txt 

在腳本中,你會掃描參數,在投入一個陣列之前:::一切,一切後,第二陣列。

while (($# > 0)); do 
    f=$1 
    shift 
    if [[ $f = ::: ]]; then 
     break 
    fi 
    AVROFILES+=("$f") 
done 

FILES=("[email protected]") 

for avrofile in "${AVROFILES[@]}" 
do 

    # do some stuff with the avrofile 

    # reading the files 
    for f in "${FILES[@]}" 
    do 
     # reading every line in on from the file 
     while read line 
     do 

     done <"$f" 

    done 
done 
0

你在做什麼可能是最簡單的方法。如果沒有引號,則評估星號,腳本會獲取兩個文件名列表。

例:腳本列出所有參數:

$ cat files.sh 
#!/usr/bin/env bash 

i=0 

for arg; do 
    let i++ 
    echo \$$i is $arg 
done 

$ ./files.sh test-00* test-01* 
$1 is test-000.delme 
$2 is test-001.delme 
$3 is test-002.delme 
$4 is test-003.delme 
$5 is test-004.delme 
<snip> 

$ ./files.sh "test-00*" "test-01*" 
$1 is test-000.delme test-001.delme test-002.delme test-003.delme test-004.delme test-005.delme test-006.delme test-007.delme test-008.delme test-009.delme 
$2 is test-010.delme test-011.delme test-012.delme test-013.delme test-014.delme test-015.delme test-016.delme 
+0

通常,他的方法不允許包含由shell特別解釋的空格或其他字符的文件名。 – chepner

+0

您可以使用單引號,禁用內容的解釋。 – chw21

+0

這可以防止引用字符串中的參數擴展,這不是問題。 – chepner