Shell variable - put in the ALPHABETICAL range

Is there a way to put a variable in the ALPHABETICAL range? This does not work.

read -p "Where I should start?" start #there will be entered one small letter
for aaa in {$start..z}; do #how put variable $start in range?
...
done

Thanks for the answer.

+4
source share
4 answers

Use evalto expand a variable:

$ s=t
$ eval echo {$s..z}
t u v w x y z

Then your example will look like this:

read -p "Where I should start?" start #there will be entered one small letter
for aaa in $(eval echo {$start..z}); do 
echo $aaa
done

Since you have user input in eval, you can first check the start value as a single lowercase character:

read -p "Where I should start?" start #there will be entered one small letter
if [[ $start =~ ^[a-y]$ ]]; then 
   for aaa in $(eval echo {$start..z}); do 
   echo $aaa
   done
else 
   echo "Need to use a letter 'a-y'"
fi

Learn more about the Bash brace extension here.

+3
source

Unfortunately, you cannot put variables inside ranges {start..end}in bash.

This does what you want:

until [[ $s == "_" ]]; do echo $s && s=$(tr "a-z" "b-z_" <<<$s); done

tr . "_" - "z" .

:

$ s=t
$ until [[ $s == "_" ]]; do echo $s && s=$(tr "a-z" "b-z_" <<<$s); done
t
u
v
w
x
y
z

Perl, :

perl -le 'print for shift .. "z"' $s

.. "z" .

bash :

for ((i=$(LC_CTYPE=C printf '%d' "'$s"); i<=122; ++i)); do 
    printf "\\$(printf '%03o' $i)\n" 
done

for ASCII $s "z" , ASCII 122. printf , . printf escape- . Greg wiki , ASCII .

, eval , , , , . , script, , - .

+2
x=t
for I in $(sed -nr "s/.*($x.*)/\1/;s/ /\n/g;p" <(echo {a..z}))
do 
  # do something with $I
done

:

t
u
v
w
x
y
z
+1

eval.

for aaa in {a..z}; do
    [[ $aaa < $start ]] && continue
    ...
done

Overhead of comparison $aaa- $startmust be small, especially compared with the cost of launching a separate process for calculating the range.

0
source

All Articles