0

I am new to shell scripting I was wondering how do you index a string in bash For example in C++ we would do string[0] to get the first character in the string, how to do a similar thing in shell scripting?

mystring=helloworld

I want to traverse the string character by character For example in C++ I would do

for (auto i = 0;i < mystring.length(); i++)
      cout << mystring[i]
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • See [Change string char at index X](https://stackoverflow.com/q/9318021/4154375) for ways to change the character at an index in a string. – pjh Mar 16 '22 at 20:17

2 Answers2

1

Use parameter expansion. ${#mystring} returns the string length, ${mystring:offset:length} returns a substring.

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

print a[1] This is for Index Character a[2] ... a[n] you can do

{split($0,a,"") This is for character to split "" meaning split every character

nude
  • 35
  • 6