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
:
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
:
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:
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:
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:- The bash-hackers page on parameter expansion
- BashFAQ #100 ("How do I do string manipulations in bash?")
- BashFAQ #73 ("How can I use parameter expansion? How can I get substrings? [...])
- BashSheet quick-reference, parameter expansion section
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