0

Is there an easy way to populate a dynamic string with a size parameter?

lets say, we have:

Case N=1:
echo "Benchmark,Time_Run1" > $LOGDIR/$FILENAME

however, the run variable is parametric and we want to have all Time_Runs from 1 to n:

Case N=4:
echo "Benchmark,Time_Run1,Time_Run2,Time_Run3,Time_Run4" > $LOGDIR/$FILENAME

and the generic solution should be this form:

Case N=n:
echo "Benchmark,Time_Run1,...,Time_Run${n}" > $LOGDIR/$FILENAME

Is there a way to do that in a single loop rather than having two loops, one looping over n to generate the Run${n} and the other, looping n times to append "Time_Run" to the list (similar to Python)? Thanks!

Amir
  • 1,348
  • 3
  • 21
  • 44

2 Answers2

3

Use a loop from 1 to $n.

{
printf 'Benchmark'
for ((i = 1; i <= $n; i++)); do
    printf ',Time_Run%d' $i
done
printf '\n'
} > $LOGDIR/$FILENAME
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

One way to populate the output string with a single loop is:

outstr=Benchmark
for ((i=1; i<=n; i++)); do
    outstr+=",Time_Run$i"
done

It can also be done without a loop:

eval "printf -v outstr ',%s' Time_Run{1..$n}"
outstr="Benchmark${outstr}"

However, eval is dangerous and should be used only in cases where there is no reasonable alternative. This is not such a case. See Why should eval be avoided in Bash, and what should I use instead?.

pjh
  • 6,388
  • 2
  • 16
  • 17
  • eval echo "Benchmark ,Time_Run{1..$n}"|tr -d ' ' – ufopilot Mar 31 '22 at 05:46
  • @ufopilot: You don't need an `eval` here. `outstr=$(echo ...| tr ...)` should be sufficient. However, you incorporate the word _Benchmark_ also _n_ times, but according to the OP, this should occur only once at the beginning. Fixing these issues, I think it would be a good idea to post your approach as an answer. – user1934428 Mar 31 '22 at 06:50
  • @user1934428 with blank after Benchmark it's only one time. You need eval for the bash range with variable {1..$n} – ufopilot Mar 31 '22 at 07:09
  • I didn't see the blank. If you place code in a comment, enclose it between backquotes. In this way, it is formatted using a fixed space font, and we can recognize where the blanks are. – user1934428 Mar 31 '22 at 07:34
  • `eval echo "Benchmark ,Time_Run{1..$n}"|tr -d ' '` – ufopilot Apr 03 '22 at 10:06