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

标签 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}

最佳答案

在 bash 中做这样的事情:${string:3:1} 意味着:从 pos 3 处的字符(从 0 开始,因此是第 4 个字符)开始获取子字符串,并且长度 = 1 个字符。

例如:

string=abc

那么 ${string:0:1} 等于 a 并且 ${string:2:1} 等于 c

此脚本采用变量 $i 的值:因此它只采用位置 $i 处的字符。

关于linux - Bash: ${string:$i:1} 这是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23951146/

相关文章:

bash - 如何使用 Terraform 和 AWS 运行脚本,然后终止或销毁资源?

c# - 搜索字符串模式

Python:如何快速搜索集合中的子字符串?

bash - 在 Centos 服务器上的 shell 脚本中自动执行 git push 和 commit

MySQL 查询列名子字符串

linux - Bash 中的简单 int 条件没有意义

linux - 复制时如何清除Vim中的行号?

linux - 在 supervisorctl ERROR 上出现 Supervison 错误(没有这样的过程)

c - 如何判断线程是否响应唤醒调用?

linux - 最后一个进程尾部时未捕获 SIGTERM 信号