Linux bash is used to run complex commands or scripts to accomplish different tasks. Bash is generally used to work with different types of string and string data. One of the most popular operations is extracting substrings using the bash command line interface. In this tutorial, we examine how to extract substring in bash.
Extract Substring Using cut Command
The cut command can be used to extract a substring from a string. The -c option is used to specify the start and end index numbers for the substring. In the following example, we extract the string between 2-5 for the string “Ilovelinuxtect”.
$ cut -c 2-5 "Ilovelinuxtect"
lovel
Extract Substring Using awk Command
The awk command can be also used to extract substring in bash. The substring statement is used to extract from a string.
$ awk '{print substr($0,3,3)}' <<< 'Ilovelinuxtect'
ove
Extract Substring Using Substring Expansion
The echo command is used to print a given string in bash. But we can also use the echo command to extract a substring.
$ MYSTR="Ilovelinuxtect"
$ echo ${MYSTR:2:5}

Extract Substring Using expr Command
The expr command can be also used to extract substring. The substr command is used to extract substring with a start index and length information.
$ expr substr "Ilovelinuxtect" 5 5
elinu