0

I work on a bash script that uses part of filenames in order to be processed correctly. Here is example, having a filename that contains 'Catalog' in its name and this file is in pair with another file that contains 'product' in its name. There are more files and they need to be processed in a specific order, first files with "Catalog", then files with "ProductAttribute" in their names.

Have trying different things but still can not get working it. Here I have a hash table that associates the filenames

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
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
boblin
  • 13
  • 3
  • 1
    Take out the backticks: you're trying the *execute* grep's output. – glenn jackman Sep 06 '14 at 20:51
  • 1
    "doesn't work" is the worst problem description possible. What *does* happen, and how does that differ from what you expect? – glenn jackman Sep 06 '14 at 20:52
  • 1
    Please provide approximately 8 real file names of the files your are referring to. From your description, it is still unclear just what files contain "Catalog" and which contain "Product" and whether they are paired only though your "hash" table, associative array, or by some other means. – David C. Rankin Sep 06 '14 at 21:11

1 Answers1

2

Iterating over the keys of an associative array has no inherent order:

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

If you want to iterate in a particular order, you're responsible for it:

$ declare -A files=( ["Catalog"]="product" ["ProductAttribute"]="attribute")
$ keys=( Catalog ProductAttribute )
$ for key in "${keys[@]}"; do echo "$key: ${files[$key]}"; done 
Catalog: product
ProductAttribute: attribute
glenn jackman
  • 238,783
  • 38
  • 220
  • 352