简体   繁体   English

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

[英]Bash: ${string:$i:1} what does this mean?

This is the script. 这是脚本。 It reverses a string entered by the user: 它会反转用户输入的字符串:

#!/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"

I don't understand the following part of the script. 我不理解脚本的以下部分。 What is this? 这是什么? Looks like some kind of extended variable interpolation. 看起来像某种扩展变量插值。

${string:$i:1}

in bash doing something lik this: ${string:3:1} means: take substring starting from the character at pos 3 (0-based, so the 4th character), and length = 1 character. 在bash中执行以下操作:$ {string:3:1}的意思是:从pos 3处的字符(从0开始,因此是第4个字符)开始,取长度为1个字符的子字符串。

for example: 例如:

string=abc

then ${string:0:1} equals a and ${string:2:1} equals c . 然后$ {string:0:1}等于a而$ {string:2:1}等于c

This script takes the value of the variable $i : so it just takes the character at position $i . 该脚本采用变量$i的值:因此,它只采用位置$i处的字符。

It's substring expansion. 它是子字符串扩展。

from the man pages: 从手册页:

  ${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. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM