我知道要遍历字母表,一个人可以做到
for c in {a..z}; do something; done
我的问题是,我如何循环遍历前 n
个字母(例如构建一个字符串),其中 n
是命令行中给出的变量/参数。
我搜索了 SO,只找到了数字的答案,例如使用 C 风格的 for
循环或 seq
(参见例如 How do I iterate over a range of numbers defined by variables in Bash? )。我的环境中没有 seq
。
谢谢。
最佳答案
最直接的方法是将它们放在一个数组中并按索引循环:
#!/bin/bash
chars=( {a..z} )
n=3
for ((i=0; i<n; i++))
do
echo "${chars[i]}"
done
或者,如果您只希望它们以破折号分隔:
printf "%s-" "${chars[@]:0:n}"
关于bash - 如何在 bash 中循环遍历字母表的前 n 个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29287456/