2014-09-06 61 views
0

我在使用部分文件名以便正確處理的bash腳本上工作。 下面是一個示例,其名稱中包含'Catalog',且該文件與其名稱中包含'product'的另一個文件配對。 還有更多的文件需要按照特定順序處理,第一個文件帶有「目錄」,然後是名稱中帶有「ProductAttribute」的文件。使用關聯表按特定順序處理文件的Bash腳本

嘗試不同的事情,但仍然無法工作。 這裏我有過關聯數組的鍵關聯的文件名

declare -A files 
files=(["Catalog"]="product" ["ProductAttribute"]="attribute") 

for i in "${!files[@]}"; do 
    #list all files that contain "Catalog" & "ProductAttribute" in their filenames 
    `/bin/ls -1 $SOURCE_DIR|/bin/grep -i "$i.*.xml"`; 

    #once the files are found do something with them 
    #if the file name is "Catalog*.xml" use "file-process-product.xml" to process it 
    #if the file name is "ProductAttribute*.xml" use "file-process-attribute.xml" to process it 
    /opt/test.sh /opt/conf/file-process-"${files[$i]}.xml" -Dfile=$SOURCE_DIR/$i 

done 
+1

取出反引號:你正在嘗試* execute * grep的輸出。 – 2014-09-06 20:51:58

+1

「不起作用」是可能的最糟糕的問題描述。發生了什麼*,這與您的期望有什麼不同? – 2014-09-06 20:52:44

+1

請提供您所指的文件的大約8個真實文件名。從你的描述來看,目前還不清楚哪些文件包含「目錄」,哪些文件包含「產品」,以及它們是否僅通過「散列」表,關聯數組或其他方式進行配對。 – 2014-09-06 21:11:46

回答

2

迭代一個哈希表沒有內在次序:

$ declare -A files=(["Catalog"]="product" ["ProductAttribute"]="attribute") 
$ for key in "${!files[@]}"; do echo "$key: ${files[$key]}"; done 
ProductAttribute: attribute 
Catalog: product 

如果你想在一個特定的順序進行迭代,你」重新對它負責:

$ declare -A files=(["Catalog"]="product" ["ProductAttribute"]="attribute") 
$ keys=(Catalog ProductAttribute) 
$ for key in "${keys[@]}"; do echo "$key: ${files[$key]}"; done 
Catalog: product 
ProductAttribute: attribute 
+0

感謝提示Glenn。 – boblin 2014-09-07 11:49:43