extract substring from string in shell script

How to Extract Substring from String in Bash

Every Linux shell provides tons of features to work with variables and strings. Sometimes you may need to extract substring from string in bash. In this article, we will look at how to do this using parameter expansion.


How to Extract Substring from String in Bash

Here is how to extract substring from string. You can use this in almost every Linux system as well as shell, not just bash.

Here is the syntax to extract substring from string.

substr= ${variable:offset:length} 

In the above statement, we need to specify the variable containing string, the offset from where extraction must begin, and the length of substring to be extracted. Please note, the offset begins from 0 for 1st character of string, and not 1. Let us say you have the following string

string = "Today is beautiful"

Now let us look at some use cases for substring extraction.


Extract substring from string

To begin with, we will simply extract characters 3-6 using above parameter expansion.

$ string="Today is beautiful"
$ echo ${string:2:3} 
day


Extract substring till specific character from start

Here is an example to extract first N characters of your string. In this case we extract first 3 characters.

$ string="Today is beautiful"
$ echo ${string:0:2} 
To


Extract Last N characters of string

Here is an example to extract last N characters of your string. In this case we extract last 9 characters.

$ string="Today is beautiful"
$ echo ${string:(-9)} 
beautiful


Extract from specific character onward

Here is an example to extract all characters from a specific position, for example, for 3rd character onwards.

$ string="Today is beautiful"
$ echo ${string:6} 
is beautiful

In this article, we have learnt different ways to easily retrieve substring from another string. The key is to understand the syntax of parameter expansion for each use case and modify it according to your requirements.

Also read:

How to Split String into Array in Shell Script
How to Check if String Contains Substring in Bash
Shell Script to Remove Last N Characters from String
How to Find Unused IP Addresses in Network
How to Setup Email Alerts for Root Login

Leave a Reply

Your email address will not be published.