Bash Substring

To find the substring of a string from given starting position in the original string, and the length of the substring, use parameter expansion that performs substring extraction.

Syntax

The syntax to get the substring of given string in Bash is

${string:position:length}

Providing length is optional. If length is not specified, end of the string is considered as end of the substring.

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.

Example.sh

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

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.

Example.sh

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.