【问题标题】:Bash: ${string:$i:1} what does this mean?Bash: ${string:$i:1} 这是什么意思?
【发布时间】:2014-05-30 09:24:28
【问题描述】:
这是脚本。它反转用户输入的字符串:
#!/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}
【问题讨论】:
标签:
linux
bash
substring
reverse
【解决方案1】:
在 bash 中做类似这样的事情:${string:3:1} 意味着:从 pos 3 处的字符开始获取子字符串(从 0 开始,因此是第 4 个字符),并且长度 = 1 个字符。
例如:
string=abc
那么 ${string:0:1} 等于 a 并且 ${string:2:1} 等于 c。
这个脚本接受变量$i的值:所以它只接受$i位置的字符。
【解决方案2】:
是子串扩展。
来自手册页:
${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.