2014-09-06 66 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