1

I am processing some folders that each represent a page of a book. E.g. "Iliad-001" would be Book=Iliad, Page=001.

I want to iterate through all of the folders, create an array for each book and add an entry to that array for each page that is found, so that I can echo ${Iliad[@]} at the end of my script and it will give me a nice list of all the pages it found.

The catch I'm having is adding values to an array with a dynamic name. Here's the code that I think is intuitive (but clearly not right):

for j in */; do
        vol_name=$(basename "$j" | sed 's/\(.*\)-[0-9]*/\1/')
        page_name=$(basename "$j" | sed 's/.*-\([0-9]*\)/\1/')
        $vol_name+=( "$page_name" )
done    

This returns:

syntax error near unexpected token `"$page_name"'

If I change the variable assignment to this $vol_name+="( "$page_name" )" I get a little closer:

Iliad+=( 001 ): command not found
Cœur
  • 37,241
  • 25
  • 195
  • 267
Seth
  • 147
  • 2
  • 11

2 Answers2

1

I was able to make it work using eval.

BTW, you do not need to run sed.

#! /bin/bash

for j in */; do
        j=$(basename "$j")
        vol_name=${j%-*}
        page_name=${j#*-}
        eval "$vol_name+=('$page_name')"
done    
echo ${Iliad[@]}
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Wonderful answer! I guess I don't really understand what eval does. And I didn't even think about being able to remove those extra characters during the substitution. Thanks a lot! – Seth May 10 '13 at 21:39
  • 2
    @Seth: See `help eval`. It interprets the argument as a shell command. It is a very powerful but also dangerous builtin. – choroba May 10 '13 at 22:56
0

try this

declare $vol_name+=( "$page_name" )
Zombo
  • 1
  • 62
  • 391
  • 407