Bash Substring
In this Bash Tutorial, we shall learn to compute substring of a string given starting position and length of substring.
Syntax
To find substring in bash, use the following syntax :
${string:position:length}
Providing length is optional. If length is not specified, end of the string is considered end of the substring.
Example 1 – Bash Substring {Position:Length}
In this example, we will find the substring of a string, provided position and length of substring in the main string.
Bash Script File
#!/bin/bash str="TutorialKart" subStr=${str:4:6} echo $subStr
Here, position of substring in main string is 4, and length of substring is 6.
Output
~/workspace/bash$ ./bash-substring-example rialKa
Example 2 – Bash Substring {Position}
In this example, we will find the substring of a string, given only the position of substring in main string. If no length is given for substring, then the end of the main string is considered as end of substring.
Bash Script File
#!/bin/bash str="TutorialKart" subStr=${str:6} echo $subStr
Output
~/workspace/bash$ ./bash-substring-example alKart
End of string is considered as end of substring.
Conclusion
In this Bash Tutorial, we learned how to find the substring of a string in bash, with the help of examples.