Notification texts go here Contact Us Buy Now!

Finding substring of variable length in bash

Finding substring of variable length in bash

We frequently need to extract substrings from variables in bash scripting. This can be done using parameter expansion, which is a powerful feature of the bash shell.

One way to find a substring is to use the ## operator. This operator removes everything from the beginning of the variable up to and including the specified pattern. For example, the following command will remove everything up to and including the first occurrence of the = character from the variable s:

``` time_int=${s##*=} ```

The resulting value of time_int will be 1234.

If we want to remove everything up to and including the last occurrence of the = character, we can use the ##* operator. For example, the following command will remove everything up to and including the last occurrence of the = character from the variable s:

``` time_int=${s##*=} ```

The resulting value of time_int will be 1234.

We can also use the # operator to remove everything from the end of the variable up to and including the specified pattern. For example, the following command will remove everything from the end of the variable s up to and including the first occurrence of the = character:

``` time_int=${s%==*} ```

The resulting value of time_int will be time.

If we want to remove everything from the end of the variable s up to and including the last occurrence of the = character, we can use the %* operator. For example, the following command will remove everything from the end of the variable s up to and including the last occurrence of the = character:

``` time_int=${s%==*} ```

The resulting value of time_int will be time.

These are just a few examples of how to use parameter expansion to find substrings in bash. For more information, please refer to the bash man page.

References:

if time= part is constant you can remove prefix by using ${str#time=}

Let's say you have str='time=123123' if you execute echo ${str#time=} you would get 123123

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.