如何在bash中的索引处检索字符串中的字符



我是shell脚本的新手,我想知道如何在bash中索引字符串例如,在C++中,我们会使用string[0]来获取字符串中的第一个字符,如何在shell脚本中执行类似的操作?

mystring=helloworld

我想逐个字符遍历字符串例如在C中++我会做

for (auto i = 0;i < mystring.length(); i++)
cout << mystring[i]

使用参数展开。${#mystring}返回字符串长度,${mystring:offset:length}返回子字符串。

#! /bin/bash
mystring=helloworld
for ((i=0; i<${#mystring}; ++i)) ; do
printf %s "${mystring:i:1}"
done
echo "Hello" | awk '{split($0,a,""); print a[1]}'

print a[1]这是针对索引字符a[2]的。。。你可以做

{split($0,a,"")这是用于字符拆分"",意味着拆分每个字符

最新更新