I'm using a Bash script, and I have two input numbers. For simplicity, let's say the first variable is called Start and the second variable is Stop, and each can be a number between 1000 and 2000.

I have files that are arranged via names that match the starting two digits of each number. For example, one file is called:

/path/to/files11, which is a file corresponding to any number between (and including) 1100 to 1199

Now, given Stop and Start, I want to use a loop that sets the proper files to a string in the following manner: If Start = 1923 and Stop = 2267, then I want to do the following (pseudocode):

MyVariable = "/path/to/files19;/path/to/files20;/path/to/files21;/path/to/files22"

but I want to be able to do this for any number in my range.

Any advice on how to select the proper starting and stopping files based on the first two digits and looping over the numbers to get the right string?


2 Answers 2


Using bash


for ((i=Start/100; i<=Stop/100; i++)); do 
echo "$MyVar"

The above echo statement produces:


How it works:

  • MyVar=

    This makes sure that the variable MyVar is empty.

  • for ((i=Start/100; i<=Stop/100; i++)); do

    This starts a loop over variable i.

  • MyVar="$MyVar;/path/to/files$i"

    This appends a string to MyVar every time the loop is run.

  • done

    This signals the end of the loop.

  • MyVar=${MyVar:1}

    This removes the unwanted semicolon from the beginning of the string.

  • echo "$MyVar"

    This displays the result.

Using awk

Using very similar logic:

MyVar=$(awk -v Start=1923 -v Stop=2267 'BEGIN{for (i=int(Start/100);i<=int(Stop/100);i++) MyVar=MyVar";/path/to/files" i; print substr(MyVar,2)}')
echo "$MyVar"

The above echo statement produces:


This looks like a job for Brace Expansion, plus a bit of eval over string manipulation:

MyVariable=$(eval "printf '%s' /path/to/files{${Start:0:2}..${Stop:0:2}}\;")

You then may want to get rid of the final semi-colon via ${MyVariable%;}

In the above example I'm assuming that your ${Start} and ${Stop} truly are always at least a 3 digits number, else you will need to adjust the string manipulations.

You must log in to answer this question.