bash - 如何根据 shell 脚本中的 for 循环索引增加选项卡数
问题描述
以下是我的 for 循环
array=( one two three )
for (( i=0;i<${#array[@]};i++ ))
do
echo -e "\t${array[$i]}"
done
使用此脚本,我得到的输出为
#current output
one
two
three
但我的要求是根据 for 循环的索引增加选项卡数。
#required output
one
two
three
谁能建议如何实现这一目标?
解决方案
使用内循环:
for (( i=0; i < ${#array[@]}; ++i )) ; do
for (( j=0; j<=i; ++j )) ; do
printf '\t'
done
echo "${array[$i]}"
done
或将选项卡累积在变量中:
for (( i=0; i < ${#array[@]}; ++i )) ; do
t+=$'\t'
echo "$t${array[$i]}"
done
或者,使用具有重复运算符的 Perl:
perl -E 'say "\t" x ++$i, $_ for @ARGV' "${array[@]}"