Bash:$ {string:$ i:1}这是什么意思?

时间:2014-05-30 09:24:29

标签: linux bash substring reverse

这是脚本。它会反转用户输入的字符串:

#!/bin/bash
read -p "Enter string:" string
len=${#string}
for (( i=$len-1; i>=0; i-- ))
do
# "${string:$i:1}"extract single single character from string.
reverse="$reverse${string:$i:1}"
done
echo "$reverse"

我不明白脚本的以下部分。这是什么?看起来像某种扩展变量插值。

${string:$i:1}

2 个答案:

答案 0 :(得分:4)

在bash中执行以下操作:$ {string:3:1}表示:从pos 3处的字符开始获取子字符串(从0开始,所以第4个字符开始),长度= 1个字符。

例如:

string=abc

然后$ {string:0:1}等于a而$ {string:2:1}等于c

此脚本采用变量$i的值:因此它只需要将位置放在$i位置。

答案 1 :(得分:4)

这是子串扩展。

来自手册页:

   ${parameter:offset:length}
          Substring  Expansion.   Expands  to up to length characters of parameter starting at the character specified by offset.  If length is omitted, expands to the
          substring of parameter starting at the character specified by offset.  length and offset are arithmetic expressions (see ARITHMETIC  EVALUATION  below).   If
          offset evaluates to a number less than zero, the value is used as an offset from the end of the value of parameter.  Arithmetic expressions starting with a -
          must be separated by whitespace from the preceding : to be distinguished from the Use Default Values expansion.  If length evaluates to a  number  less  than
          zero,  and  parameter  is  not @ and not an indexed or associative array, it is interpreted as an offset from the end of the value of parameter rather than a
          number of characters, and the expansion is the characters between the two offsets.  If parameter is @, the result is length positional  parameters  beginning
          at  offset.   If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${parameter[offset]}.
          A negative offset is taken relative to one greater than the maximum index of the specified array.  Substring expansion applied to an associative  array  proâ
          duces  undefined  results.  Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion.
          Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default.  If offset is 0, and the posiâ
          tional parameters are used, $0 is prefixed to the list.