3

I have an array:

allChapters=('1' '2' '3' '4' '5' '6' '7' '8' '9' '10' '11' '12' '13' '14' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I')

I need to run a command that takes specifying parameters like:

prince index.html 1.html 2.html 3.html 4.html 5.html 6.html 7.html 8.html 9.html 10.html 11.html 12.html 13.html 14.html A.html B.html C.html D.html E.html F.html G.html H.html I.html  -o doc.pdf

Is there a way to expand an array without manually typing it all so I can just add to the array and not have to modify the command?

Something like:

prince ${allChapters[*]}.html -o doc.pdf
GameDeveloper
  • 1,029
  • 1
  • 7
  • 12

1 Answers1

8

This works:

prince "${allChapters[@]/%/.html}" -o doc.pdf

That replaces the empty string at the end of each entry with the desired extension.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Fantastic. Thank you for this! Where could I have looked this up? Googling wasn't helpful for a reference doc. – GameDeveloper Apr 20 '15 at 17:52
  • 1
    Go to the source: the [GNU bash manual](https://www.gnu.org/software/bash/manual/bashref.html). In this case, the answer is in the [parameter expansion](https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion) section. Scroll down to read about `${parameter/pattern/string}` and you'll find: "If *parameter* is an array variable subscripted with ‘@’ or ‘*’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list." – glenn jackman Apr 20 '15 at 18:48