Bash – Get character at specific index in string
To get character at specific index in a string in Bash scripting, you can use the following syntax.
${string:index:1}
where
index
is the specific position from which we would like to extract the character instring
.:1
afterindex
specifies that we would like to extract only one character from thestring
.
Example
In the following script, we take a string in str
. We get the character at index=5 using the expression given above.
example.sh
#!/bin/bash str="abcdefghihklm" index=5 ch=${str:index:1} echo $ch
Output
sh-3.2# ./example.sh f
References
ADVERTISEMENT
Conclusion
In this Bash Tutorial, we learned how to get the character at specific index from given string.