'How to retrieve a character in a string at a index in bash [duplicate]
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]
Solution 1:[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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | choroba |
| Solution 2 | nude |
