0
for seq in {046725..046899}
do
   #body
done

Above segment of code runs beautifully keeping preceding zeroes in seq variable but why following code segment doesn't run? Is there any way? I need seq variable in for loops to have preceding zeroes if there is any preceding zeroes.

lowest=046725
highest=046899
for seq in {$lowest..$highest}
do
  #body
done

3 Answers3

2

"Brace expansion is performed before any other expansions" - from bash manual. Variable expansion followed after.

appomsk
  • 314
0

You should be able to accomplish this with the following code:

#!/bin/bash

lowest=046725
highest=046899
width=6

for (( seq=10#$lowest; seq<=10#$highest; seq++))
  do

    length=`echo -n $seq | wc -c`

    if [[ $length < $width ]]; then

      number_of_zeroes_to_add=`expr $width - $length`

      for zeroes in `seq $number_of_zeroes_to_add`;
        do echo -n 0;
      done

    fi

    echo $seq


done

What this is doing is establishing a width of the number (e.g. 6 characters wide), identifying numbers that don't meed this width because the leading zeros have been truncated off, and then reinserting them.

0

Brace expansion {...} is very ahead of Parameter Expansions ${..}.

One way to re-process the line and get the values inside $var to perform the Brace expansion is to use eval (Not recommended and not really needed in this case):

lowest=046725
highest=046899
for for seq in $(eval echo {$lowest..$highest});
do
    #body
done

It is better if the numbers for the limits do not have leading zeros, but if they do, this will also convert them.

The output will have a leading zero, as requested. And is controlled by the single printf. Change the 06 to 07 if you need two zeros.

#!/bin/bash

lowest=046725              highest=046899

seq="$(( 10#$lowest ))"    max="$(( 10#$highest ))"

while    (( seq <= max ))
do       printf '%06d\n' $(( seq++ ))
done

If you need the result in a variable, use this line (and use var):

do       printf -v var '%06d\n' $(( seq++ ))

And a sh version:

#!/bin/sh

lowest=00046725    highest=000046899

seq=${lowest#"${lowest%%[!0]*}"}
max=${highest#"${highest%%[!0]*}"}

while    [ $seq -le $max ]
do       printf '%06d ' "$seq"
         seq=$(( seq + 1 ))
done